To allow the program to respond to user operations as soon as possible, the thread is often used when developing Windows applications.
If a thread is not used for time-consuming operations, the UI interface will be stuck for a long time. In this case, the user is reluctant to see it, in this case, we want to use threads to solve this problem.
First look at a piece of code:
btnStartThread_Click( progressBar.Value = Thread thread = Thread( (progressBar.Value < }
The Program Interface contains a button and a progress bar.
The intention is to click the "Start" button to start a simulated operation and display the overall progress of the operation in the progress bar. However, if we really click the "Start" button, it will disappoint because it will throw a System. invalidOperationException exception. The exception description is "Inter-thread operation is invalid: It is accessed by a thread that does not create the control 'ssssbar."
Solution 1: checkforillegalcrossthreadcils attributes
This is because.. NET does not allow the use of threads in the debugging environment to access the UI control created by itself, this may be caused by unpredictable operations on interface controls in a multi-threaded environment. If developers can confirm that their code operation interfaces will not be faulty, A simple solution is to set the static attribute checkforillegalcrossthreadcils. The default value is true. If it is set to false, in the future, the operation interface will not throw an exception in the multi-threaded environment. The above code can be modified:
btnStartThread_Click(= = ; Thread thread = Thread( (progressBar.Value <
Solution 2:
Invoke method to operate the interface
SetProgressBarValue( btnStartThread2_Click(= = Thread( value = (value < .Invoke( SetProgressBarValue(SetProgressValue), ++= ++ SetProgressValue( progressBar.Value =
Solution 3:
BackgroundWorker Interface
btnBackgroundWorker_Click(= = += backWorker.ProgressChanged += backWorker.RunWorkerCompleted += = ; backWorker.WorkerSupportsCancellation = ; backWorker.RunWorkerAsync();= worker_RunWorkerCompleted(= worker_ProgressChanged( progressBar.Value = worker_DoWork( value = (value <++value);
Solution 4: Timer mode
btnTimer_Click(= System.Windows.Forms.Timer timer = = += = timer_Tick( value = (value <= value +