C # Several ways to perform asynchronous operations comparison and summary

Source: Internet
Author: User

C # Several ways to perform asynchronous operations comparison and summary0x00 Introduction

Before writing a program, when encountering some time-sensitive operations such as HTTP requests, always new thread processing. The Xxxxxasync () and other methods have not been known, but also did not encounter any major problems. Recently, because of the requirements of the DevExpress write interface, ran up found than the native control efficiency is much worse. This is the thought of the "golden rule": Do not perform interface-independent operations on the UI thread, so focus on the asynchronous operation of C # and share your own comparisons and summaries.

0x01 test method

ide:vs2015 Community

. NET version: 4.5

Using a function to sleep randomly for 100 to 500 milliseconds to simulate time-consuming tasks, and to return a task that was spent, calling this method on the UI thread would cause blocking, causing the UI to feign death, so it would need to perform this task asynchronously and show the time spent in the information output area.

Different types of asynchronous operations are tested in the main interface through a variety of different buttons

0x02 using thread for asynchronous operations

The method of using ThreadPool for asynchronous operations is as follows, and it is important to note that IsBackground defaults to false, which means that the thread that swapped it with does not produce a dependency, and the thread does not end when the calling thread exits. Therefore, you need to set IsBackground to true to indicate that the thread is a background thread, so that the thread will end when the main path exits. In addition, the UI can be manipulated across threads or Dispatcher.begininvoke (), and Dispatcher.invoke () may be used if a blocking UI thread is needed.

0X03 using ThreadPool for asynchronous operations

The ThreadPool (thread pool) appears primarily to increase the reuse of threads (similar to the pool of connections that access the database). Thread creation is a relatively expensive behavior, in order to achieve a better interactive experience, development may be a lot of use of asynchronous operations, especially the need to frequent a large number of short-time asynchronous operations, frequent creation and destruction of the thread will cause a lot of waste of resources. While some threads are stored through the thread pool, when a new thread is required to perform an operation, an already existing idle thread is removed from the thread pool, and if there are no idle threads at this time, and the number of threads in the thread pool does not reach the thread pools, a new thread is created and then put back into the thread pool after the use is complete. This can greatly eliminate the overhead of thread creation. The minimum and maximum number of threads in a thread pool can be specified, but in most cases there is no need to specify that the CLR has a policy to manage the thread pools. The use of ThreadPool is very simple, as shown in the code below. Working with the UI across threads still needs to be dispatcher.

0X04 uses task for asynchronous operations

Task is also getting threads from the thread pool when it is asynchronous, but the supported operations are richer. and task<t> can support the return value, the ContinueWith () of the task can pass the return value to the operation after the end of the task execution, but the UI is still required to operate across threads in continuewith with dispatcher. In addition, the task can also perform asynchronous operations directly using the static method Task.run<t> ().

0x05 using async/await for asynchronous operations

This is a new feature in C#5, when an await is encountered, a thread is taken out of the thread pool to perform an await wait operation asynchronously, and the method returns immediately. When the asynchronous operation is finished, return to the place where the await is located and then execute it backwards. Await requires a function that waits for the async task<t> type. The detailed use method may refer to the related material, the test code is as follows. The asynchronous end is returned to the calling thread, so modifying the UI does not require dispatcher.

You can also wrap the testtask into an async method so that you can work with two lines of code that are commented out. The wrapped async method is as follows:

Async/await also takes threads from the thread pool, implements thread reuse, and the code is simple and easy to read, returning the calling thread automatically when an asynchronous operation returns, and is the preferred way to perform asynchronous operations. And although it is a new feature of c#5, c#4 can support async/await by downloading the upgrade package.

0x06 about efficiency

The method above attempts to use thread pools directly or indirectly to fetch threads, in addition to using thread directly. Theoretically, when creating a thread, the thread is allocated stack space, the thread destroys the memory, and the creation thread increases the CPU's work. Therefore, you can continuously create threads and record the time consumed to test performance. The test code looks like this:

When the thread is tested, the memory and CPU will have a small bump every time the test is created continuously, but the thread will drop down soon after it is finished, and it would take about 120-130 milliseconds to create 100 threads consecutively on my computer. :

Test results:

When you use thread pool-based methods to create threads, sometimes the first time is slightly slower, it should be that the thread pool is out of line, the time overhead is 0-15 milliseconds, and the first time the memory is created increases. The time spent at the back of the test is 0 milliseconds, the memory performance is also very stable, the CPU overhead distribution is more average. Test results:

0X07 Conclusion

You should use a thread pool-based operation when you perform an asynchronous operation, giving precedence to the Async/await method from the simplicity and readability of your code. For the older. NET version can use task or ThreadPool. The thread can be used if the following conditions are met:

1. After the thread is created, it needs to work continuously to exit the main path. In this case, even using thread pool threads will not be returned and cannot be reused, and thread can be used.

2. Threads are still required to execute after the main thread exits, and this situation uses thread pool threads that do not meet the requirements, need to use thread and develop IsBackground to False (default).

0x08 Related Downloads

Test program code in: Https://github.com/durow/TestArea/tree/master/AsyncTest/AsyncTest

C # Several ways to perform asynchronous operations comparison and summary

Related Article

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.