Control actions on C # child threads
In general, a control operation on a form directly on a child thread can cause an exception. This is because the child threads and the threads running the form are different spaces, so it is not possible to manipulate the controls on the form in a child thread simply by using the control object name, but rather than not being able to operate, Microsoft provides Invoke method, whose function is to let the child thread tell the form thread to complete the corresponding control operation.
Now with a thread-controlled process bar to illustrate, the approximate steps are as follows:
1. Create an invoke function, roughly as follows:
/// < summary>
/// Delegate function to be invoked by main thread
/// < /summary>
private void InvokeFun()
{
if( prgBar.Value < 100 )
prgBar.Value = prgBar.Value + 1;
}
2. C # Child thread entry function:
/// < summary>
/// Thread function interface
/// < /summary>
private
void
ThreadFun()
{
//Create invoke method by specific function
MethodInvoker mi =
new
MethodInvoker(
this
.InvokeFun );
for
(
int
i = 0; i < 100; i++ )
{
this
.BeginInvoke( mi );
Thread.Sleep( 100 );
}
}
3. To create a C # child thread:
Thread thdProcess =
new
Thread(
new
ThreadStart( ThreadFun ) );
thdProcess.Start();
Note:
using
System.Threading;
private
System.Windows.Forms.ProgressBar prgBar;