Controls that do not support multithreaded direct access interface after c#2005 (the interface creation thread is not the same thread as the access thread), but can be resolved using delegate:
1. Declare a delegate and define a delegate implementation function
View Plaincopy to Clipboardprint?
delegate void showprogressdelegate (int newpos);
private void showprogress (int newpos)
{
Determine if access is available in the thread
if (!_progressbar.invokerequired)
{
No, No. Direct manipulation of controls
_progressbar.value = Newpos;
}
Else
{
Yes then enable delegate access
ShowProgressDelegate showprogress = new ShowProgressDelegate (showprogress);
Using invoke will wait until the function call is over, and BeginInvoke will not wait for it to go directly backwards.
This. BeginInvoke (showprogress, new object[] {newpos});
}
}
delegate void showprogressdelegate (int newpos);
private void showprogress (int newpos)
{
Determine if access is available in the thread
if (!_progressbar.invokerequired)
{
No, No. Direct manipulation of controls
_progressbar.value = Newpos;
}
Else
{
Yes then enable delegate access
ShowProgressDelegate showprogress = new ShowProgressDelegate (showprogress);
Using invoke will wait until the function call is over, and BeginInvoke will not wait for it to go directly backwards.
This. BeginInvoke (showprogress, new object[] {newpos});
}
}
2. Define the thread function (the interface control can be read into 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));
The method is called directly here, and is automatically judged by its internal whether delegate is enabled.
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));
The method is called directly here, and is automatically judged by its internal whether delegate is enabled.
ShowProgress (Newpos);
Thread.Sleep (100);
}
}
3. Startup and termination of threads
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 end of the thread to continue
_progressthread.join ();
_progressthread = null;
The above is the content of C # multithreaded access interface, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!