C# background processing

Here’s a quick reminder on how to not tie up you form thread while
doing time consuming operations from controls on a form. .NET
makes this relatively easy:

1. Declare your delegate:

private delegate void CallAsyncWorkerDirectDelegate(string func, string param);

2. Write your Worker function

private void CallAsyncWorkerDirect(string func, string param)
{
string parm1, parm2;
parm1 = func;
parm2 = param;
// Do you time intensive stuff here
}

3. Finally, in your eventhandler:

private void button_Click(object sender, EventArgs e)
{
string parm1, parm2;
parm1 = textBox1.Text;
parm2 = textBox2.Text;
CallAsyncWorkerDirectDelegate wrkr = new CallAsyncWorkerDirectDelegate(CallAsyncWorkerDirect);
wrkr.BeginInvoke(parm1, parm2, null, null);
}

Now if you run into the case where you need to update
controls on the form in your worker delegate, you won’t be allowed to do
this in your worker thread because of thread affinity. To get
around this, create a formUpdate delegate and use this.Invoke to call
it:

1. Again, declare your delegate

private delegate void UpdateFormDelegate(string func);

2. Define your UpdateForm function

private void UpdateForm(string func)
{
label5.Text = "success!";
}

3. Finally, you can get your worker thread to notify the form when it’s done:

private void CallAsyncWorkerDirect(string func, string param)
{
string parm1, parm2;
parm1 = func;
parm2 = param;
// Do you time intensive stuff here
//Run updates to the form in the same thread as all controls
this.Invoke(new UpdateFormDelegate(UpdateForm), new object[] { parm1 });
}

Hope I’ll remember this!

Comments are closed.