Saturday, April 17, 2010

AsyncOperationManager for WinForm

To run a process in a thread that is other than UI, you may use the following:

1. BackgroundWorker class - allows you to post the progress in integer type only.
2. AsyncOperationManager class - allows you to post any object into the method that is running in the UI context.

If you need to pass the information to be shown in the UI, AsyncOperationManager is much more flexible.

Below is the sample code on using the AsyncOperationManager class.

private void button3_Click(object sender, EventArgs e)
{
AsyncOperation ao
= AsyncOperationManager.CreateOperation(null);

Thread t = new Thread(new
ParameterizedThreadStart(DoRun2));
t.Start(ao);
}

public void DoRun2(object state)
{
AsyncOperation ao = (AsyncOperation)state;

int j;

for (int i = 0; i < 100; i++)
{
j = tl.id;
ao.Post(this.DoProgress2, i);
System.Threading.Thread.Sleep(90);
}

ao.OperationCompleted();
}
void DoProgress2(object state)
{
// you don't have to call label2.Invoke() method because
// ao.Post() will put the context back to the UI
// context automatically.
this.label2.Text = state.ToString();
}