Constraints on Windows Forms architecture:
No member of the UI can be called by other threads (worker threads) other than the UI thread.
For example:
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Windows. forms;
Using system. Threading;
Namespace Test
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
Public Delegate int onadd (int I, Int J );
Int add (int m, int N)
{
Int sum = m + N;
Button1.text = sum. tostring ();
Return sum;
}
Private void button#click (Object sender, eventargs E)
{
Onadd proc = add;
System. iasyncresult async = Proc. begininvoke (1, 1, null, null );
// The following two lines are waiting for proc to complete.
// Reflection (assuming intadd takes some time to complete), you need to comment them out.
Int sum = Proc. endinvoke (async );
Console. writeline (SUM );
}
}
}
The asynchronous delegate call accesses button1.text through the thread in the thread pool. An error occurred!
Correct UI update method:
Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. text;
Using system. Windows. forms;
Using system. Threading;
Namespace Test
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
Public Delegate int onadd (int I, Int J );
Public Delegate void onupdateui (Object sender, string text );
Int add (int m, int N)
{
Int sum = m + N;
// Button1.text = sum. tostring ();
Object [] plist = {This, Sum. tostring ()};
Button1.begininvoke (New onupdateui (updateui), plist );
Return sum;
}
Private void updateui (Object sender, string text)
{
Button1.text = text;
}
Private void button#click (Object sender, eventargs E)
{
Onadd proc = add;
System. iasyncresult async = Proc. begininvoke (1, 1, null, null );
// The following two lines are waiting for proc to complete.
// Reflection (assuming intadd takes some time to complete), you need to comment them out.
Int sum = Proc. endinvoke (async );
Console. writeline (SUM );
}
}
}
Http://www.microsoft.com/china/MSDN/library/enterprisedevelopment/softwaredev/misMultithreading.mspx? MFR = true
To be continued...