Tuesday, October 24, 2006

C# equivalent CSingleLock / Critical Section  [Digg.com This!]

C# has a pretty nifty way to perform critical section locking using the newly created 'lock' statement. For those of you after the quick answer:

Object lockobj = new Object();
lock (lockobj)
{
// Do your locked work
}

To offer a bit more information..

When would you use this?

Critical sections are used when you need to operate on objects, files, or other resources such as database and TCP connections across a number of threads.

If you have multiple threads all trying to write to a file at the same time, for instance (say a log file), what happens if threads try writing at the same time? One thread may get an exception saying it cannot open the file, or worse you may end up losing data if you don't correctly catch the exception.

How does it work?

Quite simply the lock statement will check if the object is locked and if it is it will wait. Once the existing lock is relinquished the waiting thread will then move into the code within the braces and perform its operations.

If you want the full technical details please visit the MSDN.

Friday, April 28, 2006

Copying one string array to another  [Digg.com This!]

Say you have an array origArray declared as:

string[] origArray;

that contains a number of string items created, for example, like this:

origArray = csvLine.Split(',');

I wanted to copy those strings into a new array dependent on some criteria. This can be achieved as so:

// Create new empty array
string[] outArray = new string[origArray.Length];

for (int i = 0; i <>
{
outArray[i] = (string)tagArray[i].Clone();
}

(I'm missing my criteria, but I have an if statement before I do the clone and do something else otherwise.)

Thursday, March 23, 2006

Running command line apps from C#  [Digg.com This!]

Here's a great article on the MSDN blog for how to run a command line app from your C# code. Here it is:

http://blogs.msdn.com/csharpfaq/archive/2004/06/01/146375.aspx

If you want the quick NON-SYCHRONOUS method, try:

System.Diagnostics.Process.Start(@"c:\myscript.bat");

Thursday, March 16, 2006

Convert char[] to string  [Digg.com This!]

char[] is quite convenient if you're reading file data using StreamReader, but it doesn't offer the same functionality as string does. Here's one way I've found of converting:

char[] charBuf = new char[1024]; // Example char array

string s = ""; // Example empty string

s = new string(charBuf); // Create new string passing charBuf into the constructor

Sunday, June 05, 2005

CString::Find C# equivalent  [Digg.com This!]

The C# equivalent of CString::Find is IndexOf, which works for both string and System.String.

Code in Visual C++ / MFC:

CString sData = "http://www.calcaria.net";

int iColonPos = sData.Find(":");


Code in C#:

string sData = "http://www.calcaria.net";

int iColonPos = sData.IndexOf(":")