Friday, November 30, 2012

Multi-threading with C#

Ok, I worked on multi-threaded applications in C# in the past. Now I'm back to do something again.

Some notes:

1. Below 2 are the same for C# 2.0 and after, ThreadStart can be omitted (but can be useful say when you want to start a group of functions):

    1) Thread newThread = new Thread(new ThreadStart(this.checkProcesses)); 
    2) Thread newThread = new Thread(this.checkProcesses); 

2. The new thread by default is not a background process, which means when the GUI exits, it continues to run in the background. If you set it as a background process, then GUI exit will cause it to exit as well (usually this is desired):

    newThread.IsBackground = true; // usually desired.

3. Access of GUI control needs special handling using Invoke() method:

    delegate void SetTextCallback(string a, string b);
    private void setMsg(string a, string b) {
        if (this.textBox1.InvokeRequired) {
            SetTextCallback d = new SetTextCallback(setMsg);
            this.Invoke(d, new object[] { s, b });
        }
        else { this.textBox1.Text = a + b; }
    }

Then call the setMsg method in the thread method: this.setMsg("hello, ", "world");

Ways of using multi-threading:

    // Method 1. basic method.
    Thread newThread = new Thread(this.checkProcesses); 
    newThread.IsBackground = true; 
    newThread.Start();

    // Method 2. use BackgroundWorker. 

References:

[1] Multi-process: http://msdn.microsoft.com/en-us/library/6x4c42hc.aspx
[2] Multiple process, access form control: http://msdn.microsoft.com/en-us/library/ms171728%28v=vs.80%29.aspx
[3] Background worker: http://stackoverflow.com/questions/363377/c-sharp-how-do-i-run-a-simple-bit-of-code-in-a-new-thread

No comments:

Blog Archive

Followers