Event-driven asynchronous mode
Objective
What do you mean, events ? What do you mean drive? ? What's the asynchronous thing? ? I know all these words, one by one. , but I don't know what it means to practice. , Don't worry . , look down . .
In the next article , I'll specialize in concurrency , synchronization , asynchronous, and event-driven technology .
event-based Asynchronous (EAP)provides a simple way of handling in a multithreaded environment.
It has several features:
1. Support Cancellation
2. The WPF or windows Form space can be updated safely
3. The exception information can be queried in the completion event .
4. "In the background" performs time-consuming tasks ( such as downloads and database Operations ), but does not end your application
5. Perform multiple operations at the same time and receive a notification when each operation completes .
6. Wait for the resource to become available but not stop ("hang") you have to the application
7. Communicating with a pending asynchronous operation using a familiar event and delegate model
EAP is just a pattern , So these features must all be implemented by the implementation . in the . NET There are a few classes that support this pattern , The most famous is BackgroundWorker and the System.Net.WebClient the .
The essence of this pattern is that each class provides a number of similar members to manage multithreading , For example :
Public byte[] Downloaddata (Uri address); public void DownloadDataAsync (Uri address); public void DownloadDataAsync (Uri address, Object usertoken); public event Downloaddatacompletedeventhandler downloaddatacompleted; public void CancelAsync (); Cancels the operation public bool IsBusy {get;}//Gets whether the information is running.
Here's an example of using WebClient :
Class program { static void Main (string[] argss) { var WC = new WebClient (); Wc. downloadstringcompleted + = (sender, args) = { if (args. Cancelled) { Console.WriteLine ("Canceled"); } else if (args. Error! = null) { Console.WriteLine ("Exception:" + args. error.message); } else { Console.WriteLine (args. Result.length + "chars were downloaded"); } ; Wc. DownloadStringAsync (New Uri ("http://www.cnblogs.com/LoveJenny/")); Console.ReadLine (); }
Analysis : Although a WebClient has multiple async methods , they all share the same cancelasyc and the IsBusy Properties , so there can only be one asynchronous operation at a time .
BackgroundWorker
BackgroundWorker is A helper class for managing worker threads under System.ComponentModel , which provides the following features .
1. Support Cancellation
2. The WPF or Windows Forms controls can be updated safely
3. The exception information can be queried in the completion event .
4. Progress can be reported
5. Because the IComponent interface is implemented , It can be used by the designer .
6.BackgroundWorker uses a thread pool , which means you can never call on a backgroundworker thread Abort Method .
Class program { static BackgroundWorker _BW = new BackgroundWorker (); public static void Mainthread () { _BW. DoWork + = new Doworkeventhandler (_bw_dowork); _BW. RunWorkerAsync ("Message to Worker"); Console.ReadLine (); } static void _bw_dowork (object sender, DoWorkEventArgs e) { Console.WriteLine (e.argument); Do some time-consuming things for (int i = 0; i < 100000; i++) { Console.WriteLine (i); } } static void Main (string[] argss) { mainthread (); Console.ReadLine (); }
The following example implements the progress report
Using system;using system.collections.generic;using system.componentmodel;using system.linq;using System.Text;using System.threading;using System.Threading.Tasks; Namespace Event Async {class Program {static void Main (string[] args) {threadbackgroundworker.ma Inthread (); Console.ReadLine (); }} class Threadbackgroundworker {static BackgroundWorker _bw; public static void Mainthread () {_BW = new BackgroundWorker {WORKERREPORTSPR ogress=true,//Allow report progress workersupportscancellation =true//allow cancellation}; _BW. DoWork + = new Doworkeventhandler (_bw_dowork); _BW. ProgressChanged + = new Progresschangedeventhandler (_bw_progresschanged); _BW. runworkercompleted + = new Runworkercompletedeventhandler (_bw_runworkercompleted); _BW. RunWorkerAsync ("Hello to Worker"); Console.WriteLine ("Press Enter in the next 5 seconds to canCel. "); Console.ReadLine (); if (_BW. IsBusy) {_BW. CancelAsync (); } console.readline (); } static void _bw_runworkercompleted (Object Sender,runworkercompletedeventargs e) {if (E.cancell ED)//whether to cancel {Console.WriteLine ("You canceled!"); } else if (E.error!=null) {Console.WriteLine ("Worker Exception" +e.error.tostring ()); } else {Console.WriteLine ("Completed" +e.result); }} static void _bw_progresschanged (object sender, ProgressChangedEventArgs e) {//Output progress report Console.WriteLine ("Reacher" +e.progresspercentage+ "%"); } static void _bw_dowork (object sender, DoWorkEventArgs e) {for (int i = 0; I <=100; i+=20) {if (_BW. cancellationpending) { E.cancel = true; Return } _BW. ReportProgress (i);//Report Progress Thread.Sleep (1000); } E.result = 123; } }}
Analysis:I don't know what this is, though.,What do you want?,but looking at the output, it feels so cool.,It's gorgeous.,if it's used somewhere else ,,like when you're at home on a Web page.,prompt you to load the situation,How much do you suggest when you're on the next piece?,It's cool if you use a good feeling.,Ben Caishuxueqian No learning .,don't know how to apply,wait till you take it slow..
A little knot, please.
Tell the truth.,These things are beyond my personal understanding.,I don't know what that means.,but it was just a bite to finish.,because I think it's like when I was a kid, the teacher let me carry Zi Jing.,that's when I was in elementary school.1Grade,The words are not recognized,let alone understand what Zi Jing means.,but I was carrying it.,as we grow older,,I'm going to understand what it means.,I believe that scholarship is similar .,now because I'm not,Don't understand,you don't learn .,that must be the future .!
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Event-driven asynchronous mode