Execute Code (. NET) in the UI thread)

Source: Internet
Author: User

I haven't written a blog for a long time. Refactoring recentlyCodeYou have encountered many meaningful problems.

As you know, when using asynchronous Io or a large number of multi-threaded code, synchronization problems will always occur. For example, when other threads call winform control-related code, exceptions will occur. RecentIt is found that the message structure of the UI thread needs to be used for normal operation of the wavein and waveout of naudio. They will create invisible windows in the background.. If you call the method of the wave series directly in the asynchronous Io callback of the socket, it will be abnormal or there will be no response. (Inxxx series Asynchronous Method callback is called in a thread pool)

WindowsProgramThere is only one UI thread, and all UI-related updates should occur on the UI thread to ensure security. Therefore, in actual work, we need to learn how to turn to the UI thread to execute code (or notify the UI thread to execute some code) in a non-UI thread ), here are two basic methods:

1. Use Control. Invoke of winform

Each control of winform has an invokerequired attribute and a method (invoke) used to execute code in the UI thread. The control. invokerequired attribute indicates whether the current thread creates a control thread. Therefore, this method generally has the following structure:

1 ...2 3 If(Anycontrol. invokerequired)4 {5Anycontrol. Invoke (NewAction (Delegate{Mycontrol. dosomething ();}));6}

Note that invoke can accept any delegate,But the delegate must be a certain delegate.: If the above Code does not have specific conversions such as new action or new methodinvoker, C # will report an error because it does not know which delegate to use, because many delegate match the signature that does not return a value if no parameter is set. If delegate has a return value, the invoke method returns that value. Control also implements ininvoke and endinvoke to execute asynchronous calls, but it is generally not used.

This method has a limitation that you have referenced the UI control in the context. In many cases, the background Code does not reference the UI control, which is inconvenient.

2. Use synchronizationcontext

System. Threading. synchronizationcontext is the final mechanism of code execution between threads on the. NET platform. Here I will only talk about its usage in the UI thread. For other users, let's look at msdn :)

UseSynchronizationcontext. CurrentObtains the synchronizationcontext of the current thread. Not all threads have synchronizationcontext, but the winform UI thread must have one (guaranteed by Microsoft ), therefore, at the beginning of the program, we can get the context of the UI thread in the form initialization code, which is included in the variable or passed to the background code. After that, we can call the following two methods to execute code in the UI thread (for example, display the updated interface:

1 //Run the code synchronously and wait for the response. The second parameter is the method parameter. If no code is available, null is used.2M_uicontext.send (Delegate{Dosomething () ;}, null );3 //Run the code asynchronously and return immediately. The second parameter is the same as above.4M_uicontext.post (Delegate{Dosomething () ;}, null );

There is no difference between the two methods, because we try to keep the UI thread as few operations as possible and ensure that the UI will not be freeze, so the execution will be completed soon.

The above simple introduction is expected to be useful. If anyone else knows other methods, please come up with them ;)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.