After C#2005, multi-threaded direct access to interface controls is no longer supported (the interface creation thread and the access thread are not the same thread), but it can be solved by 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 whether the access is in the thread
if (!_progressBar.InvokeRequired)
{
// If not, operate directly Control
_progressBar.Value = newPos;
}
else
{
// If yes, enable delegate access
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);
// If you use Invoke, it will wait until the function call is completed, but BeginInvoke will not wait direct Go back
this.BeginInvoke(showProgress, new object[] { newPos });
}
}
delegate void ShowProgressDelegate(int newPos);
private void ShowProgress(int newPos)
{
// Determine whether it is in the thread Access
if (!_progressBar.InvokeRequired)
{
// If not, operate the control directly
_progressBar.Value = newPos;
}
else
{
// If yes, enable delegate access
ShowProgressDelegate showProgress = new ShowProgressDelegate(ShowProgress);
// If you use Invoke, you will wait until the function call ends, but BeginInvoke will not wait and go straight back.
this.BeginInvoke(showProgress, new object[] { newPos });
}
}
2. Define the thread function (in Interface controls can be read 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));
// The method is called directly here, and it will automatically determine whether it is enabled or not. 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));
// The method is called directly here, and it is automatically determined internally whether 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: Even if the thread does not end, the process can end
_progressThread.IsBackground = true;
_progressThread.Start();
_progressThread.Abort();
// Optional, function: Wait until the thread ends before continuing
_progressThread.Join();
_progressThread = null;
The above is the content of the c# multi-thread access interface. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!