Is the BeginInvoke method really a new thread for asynchronous call?
Refer to the following code:
public delegate void treeinvoke(); private void UpdateTreeView() { (); } private void button1_Click(object sender, e) { = "UIThread"; (new treeinvoke(UpdateTreeView)); }
Look at the running results. The pop-up dialog box shows UIThread, which shows that the delegate called by BeginInvoke is basically executed in the UI thread.
Since it is executed in a UI thread, how can we say "asynchronous execution"?
Let's take a look at the following code:
public delegate void treeinvoke(); private void UpdateTreeView() { (); } private void button1_Click(object sender, e) { = "UIThread"; Thread th = new Thread(new ThreadStart(StartThread)); (); } private void StartThread() { = "Work Thread"; (new treeinvoke(UpdateTreeView)); }
Let’s look at the running results. The pop-up dialog box is still showing UIThread. What does this mean? This shows that the delegate called by the BeginInvoke method is executed in the UI thread anyway.
So what is BeginInvoke's use?
In multi-threading programming, we often have to update the interface display in the work thread, and it is a wrong way to directly call the interface controls in multi-threading. For the specific reason, you can read this article after reading my article: How to call Winform in multi-threading. If you are a big shot, don't read this article, just read that article. Anyway, I don't understand that article much.
Invoke and BeginInvoke are a problem to solve this problem, allowing you to display the update interface safely in multi-threading.
The correct way is to encapsulate the code in the worker thread that involves the update interface into a method, and call it through Invoke or BeginInvoke. The difference between the two is that one causes the worker thread to wait, while the other does not.
The so-called "responding to operations while adding nodes" can never be relative, so that the burden on UI threads is not too great, because the correct update of the interface must always be done through UI threads. What we need to do is to take care of most of the operations in the work thread and put pure interface updates into UI threads, so that the purpose of reducing the burden on UI threads is achieved.
In that code that updates the tree node, the only code that actually works is: (100);, which gives the UI thread the opportunity to process interface messages. In fact, the Digital Ghost complicates the problem, and as long as the following code is the best work.
private void button1_Click_(object sender, e) { TreeNode tn; for(int i=0;i<100000;i++) { tn=new TreeNode (()); this.[0].(tn); if (i%100 == 0) (); } }