C #2005 and later do not support multi-thread direct access to interface controls (the interface creation thread is not the same as the access thread), but can be solved using delegate:
1. Declare a delegate and define an implementation function of a delegate.
View plaincopy to clipboardPRint?
Delegate void ShowProgressDelegate (int newPos );
Private void ShowProgress (int newPos)
{
// Determine whether the access is in the thread
If (! _ ProgressBar. InvokeRequired)
{
// If not, directly operate the control
_ ProgressBar. Value = newPos;
}
Else
{
// If yes, enable delegate access
ShowProgressDelegate showProgress = new ShowProgressDelegate (ShowProgress );
// If Invoke is used, it will wait until the function call is completed, and BeginInvoke will not wait until it goes forward directly.
This. BeginInvoke (showProgress, new object [] {newPos });
}
}
Delegate void ShowProgressDelegate (int newPos );
Private void ShowProgress (int newPos)
{
// Determine whether the access is in the thread
If (! _ ProgressBar. InvokeRequired)
{
// If not, directly operate the control
_ ProgressBar. Value = newPos;
}
Else
{
// If yes, enable delegate access
ShowProgressDelegate showProgress = new ShowProgressDelegate (ShowProgress );
// If Invoke is used, it will wait until the function call is completed, and BeginInvoke will not wait until it goes forward directly.
This. BeginInvoke (showProgress, new object [] {newPos });
}
}
2. Define thread functions (you can read interface controls in another thread)
View plaincopy to clipboardprint?
Private void ProgressStart ()
{
While (true)
{
Int newPos = _ progressBar. Value + 10;
If (newPos> _ progressBar. Maximum)
{
NewPos = _ progressBar. Minimum;
}
Trace. WriteLine (string. Format ("Pos: {0}", newPos ));
// Call the method directly here and it automatically determines whether to enable delegate.
ShowProgress (newPos );
Thread. Sleep (100 );
}
}
Private void ProgressStart ()
{
While (true)
{
Int newPos = _ progressBar. Value + 10;
If (newPos> _ progressBar. Maximum)
{
NewPos = _ progressBar. Minimum;
}
Trace. WriteLine (string. Format ("Pos: {0}", newPos ));
// Call the method directly here and it automatically determines whether to enable delegate.
ShowProgress (newPos );
Thread. Sleep (100 );
}
}
3. Thread startup and Termination
View plaincopy to clipboardprint?
Private Thread _ progressThread;
_ ProgressThread = new Thread (new ThreadStart (ProgressStart ));
// Optional. function: the process can end even if the thread does not end.
_ ProgressThread. IsBackground = true;
_ ProgressThread. Start ();
_ ProgressThread. Abort ();
// Optional. function: wait until the thread ends.
_ ProgressThread. Join ();
_ ProgressThread = null;