In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
What is the relevant operation of .NET cross-thread control? in order to solve this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
In .NET, what if an exception called across threads is generated when we access a control on a form on a non-UI thread? I introduced the use of Control.Invoke methods, if you are not used to using delegates, then .net also provides us with a component BackgroundWorker, you can use this component to handle this cross-thread control access in the form of events. Next, I will introduce the use of this component in detail.
Let's first take a look at which commonly used members BackgroundWorker provides.
Event
◆ DoWork: in this event, we perform work that requires asynchronous processing.
◆ ProgressChanged: in this event, we receive and process information during asynchronous processing.
◆ RunWorkerCompleted: in this event, we perform the work at the end of the asynchronous processing.
Method
◆ RunWorkerAsync () and RunWorkerAsync (object argument): these two methods trigger the DoWork event and start the asynchronous operation.
◆ ReportProgress (int percentProgress) and ReportProgress (int percentProgress, object userState): these two methods trigger the ProgressChanged event.
◆ CancelAsync: ends the asynchronous operation in the background.
Attribute
◆ bool CancellationPending: indicates whether the current asynchronous operation in the background is being canceled. Executing the CancelAsync method causes this property to be true.
◆ bool IsBusy: indicates whether the current background asynchronous operation is in progress, with true in progress.
◆ bool WorkerReportsProgress: gets or sets whether the current BackgroundWorker can execute the ProgressChanged method.
◆ bool WorkerSupportsCancellation: gets or sets whether the current BackgroundWorker can execute the CancelAsync method.
OK, with the above members, let's take a look at how BackgroundWorker works.
Step 1. To define an instance of BackgroundWorker, of course, you can drag a BackgroundWorker control from the toolbox onto the form or declare it directly in the code
Step 2. Generate the DoWork event and add code that needs to be executed asynchronously in the DoWork event. In asynchronously executed code, if you need to handle a control in the interface, call the ReportProgress method instead of directly handling it (such as assigning a value to the control), because the DoWork event is different from a normal interface event, which is executed on a non-UI thread, so it can be executed asynchronously.
Step 3. Generate the ProgressChanged event and add the code that the control handles, because this event is executed on the UI thread, you can assign values to the controls in the interface, and so on.
Step 4. If necessary, generate the RunWorkerCompleted event, where the business logic at the end of asynchronous execution is handled. Of course, this event is also executed on the UI thread, and you can assign values to controls in the interface and so on.
Step 5. Call the RunWorkerAsync method where you need to perform an asynchronous operation to start the asynchronous call.
Here is the specific code:
Public Form1 () {InitializeComponent (); bWorker.DoWork + = new DoWorkEventHandler (bWorker_DoWork); bWorker.RunWorkerCompleted + = new RunWorkerCompletedEventHandler (bWorker_RunWorkerCompleted); bWorker.ProgressChanged + = new ProgressChangedEventHandler (bWorker_ProgressChanged); this.Text = "UI thread id is:" + Thread.CurrentThread.ManagedThreadId.ToString ();} BackgroundWorker bWorker = new BackgroundWorker () Void bWorker_DoWork (object sender, DoWorkEventArgs e) {int tick = (int) e.Argument; Thread thr = Thread.CurrentThread; for (int I = 0; I < 30; iTunes +) {if (bWorker.CancellationPending) {e.Cancel = true; / / break;} else {Thread.Sleep (TimeSpan.FromSeconds (tick)) BWorker.ReportProgress (I, DateTime.Now.ToString () + "\\ TID:" + thr.ManagedThreadId.ToString ());} void bWorker_ProgressChanged (object sender, ProgressChangedEventArgs e) {progressBar1.Value = e.ProgressPercentage; label1.Text = e.UserState.ToString ();} void bWorker_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e) {label1.Text = DateTime.Now.ToString () ProgressBar1.Value = progressBar1.Maximum; if (e.Cancelled) label1.Text = "User cancelled.";} private void btnInvoke_Click (object sender, EventArgs e) {bWorker.WorkerReportsProgress = true; bWorker.WorkerSupportsCancellation = true; if (! bWorker.IsBusy) bWorker.RunWorkerAsync (1) } private void btnCancel_Click (object sender, EventArgs e) {if (bWorker.WorkerSupportsCancellation) bWorker.CancelAsync ();}
Please pay attention to several points in the above code:
1. Line 50, before you start calling the RunWorkerAsync method, determine whether the IsBusy property is false, because if it is true, the previous call is not finished, and another call will throw an exception.
two。 Line 56, set the WorkerSupportsCancellation property to true before calling the CancelAsync method, otherwise an exception will be thrown.
3. Line 26, set the WorkerReportsProgress property to true before calling the ReportProgress method, otherwise an exception will be thrown.
4. The parameter passed by the RunWorkerAsync method is of type object, and the value of this parameter can be obtained from the property Argument in the parameter e of the DoWork event.
5. The parameters passed by the ReportProgress method can be obtained in the parameter e in the event ProgressChanged.
6. Calling the CancelAsync method only sends a termination request to the asynchronous thread in the background, which is automatically managed by the thread.
7. In the RunWorkerCompleted event, if you want to know whether the background task has completed normal execution or was forced to interrupt by calling the CancelAsync method, please refer to the Cancelled property of the event's parameter e. (oddly enough, this property is not automatically set to true after you call the CancelAsync method, you need to set it like 20 lines in the code. )
8. Notice the code in lines 7 and 26, where the ID of the thread shows that the DoWork event and UI are executed on two different threads.
In fact, BackgroundWorker is not directly used to solve the problem of cross-thread control calls, but it provides a working mechanism that allows your program to use it to perform asynchronous calls and operate on controls during asynchronous calls.
The answer to the question about the operation of the .NET cross-thread control is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.