Tuesday, 09 October 2007
MultiThreading In CF2 with Delegates
what a frustrating problem this was. delegates weren't support in CF1, but now we have CF2 and according to microsoft
.NET Compact Framework 2.0 now supports asynchronous execution of a
delegate on a user interface thread. Unlike the
.NET Compact Framework 1.0 that supports only the Control.Invoke method (which synchronously executes a delegate on a control's owning thread), the .NET Compact Framework 2.0 provides Control.BeginInvoke that asynchronously executes a delegate on the control's owning thread. The Control.EndInvoke method is also provided. When called, the EndInvoke method returns the results of an asynchronous operation.
This is great but it's easily assumed that delegates are fully supported now in CF2, but no such luck. they don't say that calling BeginInvoke on a delegate will cause your application to crash (with a NotSupportedException) even though it will compile in visual studio without warning or error. there is an excellent (if lengthy) discussion on the matter on this newsgroup post
. the long and short of it is that you should use the ThreadPool class instead of using delegates to fire off worker threads. You can still use delegates to send a function back to the UI thread just like in winforms. Notice in the code below that the method signature of the function you are starting the thread on, requires a single 'object' parameter.
Tuesday, 09 October 2007 15:00:03 (GMT Daylight Time, UTC+01:00) .Net Compact
private void Button_Click(etc)
private void DoSomeWork(object o)