Asynchronous programming, threading, and tasks

Source: Internet
Author: User

Using the mouse to operate, we are accustomed to the delay, the past decades have been so. With the touch UI, the application requires immediate response to the user's request.

C#5.0 provides more powerful asynchronous programming with only two new keywords added: Async and await.

With asynchronous programming, method invocations run behind (usually with the help of threads and tasks ) and do not block the calling thread.

= "So asynchronous programming is supposed to be programming with threads and tasks.

In addition, asynchronous delegates are also done with the help of threads and tasks, which are event-based asynchronous patterns.

1. First understand a concept: (WPF, should be similar to windowsform)

In WindowsForm and WPF programs, the thread that owns the synchronization context is actually the UI thread. This means that the WPF element (the WPF object displayed in the window) has thread affinity, the thread that created the WPF element owns the element that is created, and other threads cannot interact directly with those WPF elements.

WPF objects that have thread affinity (which should be the WPF objects displayed in the window, or WPF visualizations) inherit from the Dispatherobject class at some point in the class hierarchy. The Dispatherobject class provides the ability to verify that the code is executing on the correct thread, and if it is not on the correct thread, to switch to the correct thread.

Dispatcher Class (Dispatcher): it inherits from the Dispatherobject base class, and any WPF visual object also inherits from the Dispatherobject base class.

Through the object. Dispather to access the scheduler that manages the object.

Members:

Dispatcher: Returns the scheduler that manages the object.

CheckAccess (): Returns True if the code uses the object on the correct thread, otherwise false.

VerifyAccess (): If the code is using the object on the correct thread, do nothing, or throw a InvalidOperationException exception.

1 //use of the Dispather scheduler2 //create a thread in the button's Click event to update the UI3 Private voidButton_Click (Objectsender, RoutedEventArgs e)4 {5Thread thread =NewThread (updatatextwrong);6 thread. Start ();7 }8 9 Private voidUpdatatextwrong ()Ten { OneTxt. Text ="Here is some new text.";//Error A     //the TextBox object captures this illegal operation by calling the Verityaccess () method.  -  -      This. Dispather.begininvoke (Dispatherpriority.normal, the(ThreadStart)Delegate() { -Txt. Text ="Here is some new text."; -});//Ok -}
View Code

The scheduler provides the Invoke () and BeginInvoke () methods.

The Invoke method marshals the specified code to the dispatcher thread (UI), and the Invoke method blocks the thread until the dispatcher executes the code that you specified. If you need to pause an asynchronous operation until the user provides some feedback through the UI, you can use Invoke ().

The BeginInvoke method provides an asynchronous pattern of the Invoke method and does not block threads.

2. What is asynchronous programming?

Three asynchronous programming in different modes: Asynchronous mode, event-based Asynchronous Pattern, task-based Asynchronous Pattern (TAP).

Asynchronous mode:

Some classes provide methods for synchronizing methods, as well as asynchronous method versions of synchronous methods, such as beginxxx and endxxx patterns .

The HttpWebRequest class provides this pattern, providing BeginGetResponse () and EndGetResponse ().

The delegate type defines the Invoke method to invoke the synchronous method, and defines a BeginInvoke method and a EndInvoke method to invoke the method in an asynchronous Pattern.

Event-based Asynchronous Pattern:

The event-based Asynchronous Pattern defines a method with an "Async" suffix.

For example, for a synchronous method the Downloadstring,webclient class provides an asynchronous Variant method Downloadasync.

More representative class: TheBackgroundWorker class implements an event-based asynchronous method. and provide progress reporting and cancellation support.

BackgroundWorker Members:

RunWorkerAsync () Method: Start execution.

DoWork Event: A time-consuming task that needs to be performed. When the BackgroundWorker object calls the RunWorkerAsync () method, extracts a free thread from the CLR thread pool and fires the DoWork event on a free thread. Therefore, it cannot access shared data, such as fields in a window class, or the user interface.

Runworkercompletedeventargs event: Triggered after the DoWork event, runs on the scheduler (UI thread).

Workerreportsprogress property: To add support for progress, it must be set to true.

ReportProgress () Method: report progress.

ProgressChanged event: Triggers when the ReportProgress () method is called to report progress. You can respond to the event, read the new progress percentage, and update the user interface. This event is raised from the user interface thread (the dispatch thread) without dispatcher.

Workersupportscancellation property: Need to add cancellation support, it must be set to true.

Cancellationpending Property: Checks whether the task is canceled. This property is typically checked in the loop operation in the DoWork event.

CancelAsync () Method: cancels the request. Calling this method does not perform any cancellation behavior, just setting the Cancellationpending property to True indicates that the user has canceled the task.

Cancel property: The setup task was canceled to complete the cancel operation.

1 //Summary of the use of BackgroundWorker components:2 //1. Handle time-consuming tasks in the DoWork event. 3 //2. If a progress report is required, set the Workerreportsprogress property to True. Calling the ReportProgress () method in the DoWork event, reportprogress () can trigger the ProgressChanged event and update the UI in the ProgressChanged event. 4 //3. If you need to cancel support, set the Workersupportscancellation property to True to perform the cancellation on other CancelAsync () methods, such as button events. The cancellation Request Cancellationpending property is then checked in the DoWork event. If the task is canceled, set the Cancel property to true to set the task to be canceled before it ends. 5 //4. In the RunWorkerCompleted event, the response to the end of the task is processed. 6 //5. Start by calling the RunWorkerAsync () method. 7 8  PublicBackgroundWorker BackgroundWorker;9Backgroundworker.runworkerasync ()//StartTen  One //DoWork Events A Private voidBcakgroundworker_dowork (Objectsender, DoWorkEventArgs e) - { -     //Update Progress the     if(backgroundworker.workerreportsprogress) -     { -Backgroundworker.reportprogress ( -); -     } +  -     //Check Cancel +     if(backgroundworker.cancellationpending) A     { atE.cancel =true;//set to cancel -         return; -     } - } -  - //runworkercompleted Events in Private voidBackground_runworkercompleted (Objectsender, Runworkercompletedeventargs e) - { to     //dosomething. + } -  the //progresschanged Events *Backgroundworker_progresschanged (Objectsender, ProgressChangedEventArgs e) $ {Panax Notoginseng     //update a task such as a progress bar - } the  + //Cancel A Private voidDocancel (Objectsender, RoutedEventArgs e) the { + Backgroundworker.cancelasync (); -}
View Code

Task-based Asynchronous mode:

With the await async keyword, there is no blocking and no need to switch back to the UI thread, which is automatically implemented.

After encountering the await keyword, the code suspends the current thread, asynchronously executes an await async method, does not block the UI thread from responding to other user requests, and then resumes execution from the suspended position when the Async method finishes executing.

You can see the following 3 in detail.

3. Basics of Asynchronous Programming (keyword Task await async async method)

There is a synchronous method greeting () that returns a string.

 Public string greeting () {   return"hello";}

Defines the method Greetingasync (), which enables the method to be asynchronous.

The task-based Asynchronous Pattern refers to the Async method name appended with async as the suffix and returns a task.

// task<string> defines a task that returns a string  Public task<string> greetingasync () {    return task<string;. Run (() =        {            return"hello";        });

Not to be continued. 13.3.2 Calling Async methods

Asynchronous programming, threading, and tasks

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.