One of the ways to call synchronous method asynchronously is using delegate BeginInvoke method.
The Delegate BeginInvoke method makes a call to the target method on a different thread from the caller of the delegate.
Why to use this method?
1- Easy to use.
2- It is possible to have a callback after the target method has completed its execution.
The problem:
Not supported in the .Net compact framework.
The following code works on .Net Framework while throws a NotSupportedException in .Net CF
//Call AsyncCall asynchronously
new ThreadHelper(AsyncCall).BeginInvoke(new AsyncCallback(Result), null);
MessageBox.Show("Should be called first");
private void AsyncCall()
{
//Wait for 2 seconds
Thread.Sleep(2000);
}
private void Result(IAsyncResult result)
{
MessageBox.Show("Should be called later");
}
delegate void ThreadHelper();
Solution:
This simple method does what we needed on the .Net CF
private void ThreadInvoke(ThreadHelper target, ThreadHelper callback)
{
ThreadStart threadStart = delegate
{
target();
callback();
};
new Thread(threadStart).Start();
}
Now the code should go like this:
//Call AsyncCall asynchronously
ThreadInvoke(delegate { AsyncCall(); }, delegate { Result(null); });
MessageBox.Show("Should be called first");
And you're done!
7eed5f07-529e-459d-bff1-4f0df1c6aa9a|1|5.0