C # Delegate, event, asynchronous

Source: Internet
Author: User

Commissioned

? A delegate can be said to be a collection of methods, with a list of methods in it, and a list of all methods when called.

? Personal Understanding:

    • When a delegate is declared and created, it is an object
    • When you invoke a method with a delegate, it is a method
declaring delegate types
delegate void MyDel(int x)

Compare filed field declarations

int  count = 5;

? Can know delegate int the correspondence, it is a type, void MyDel( int x ) corresponds tocount

Creating objects
private delegate void MyDel(int x);MyDel requestHandler =new MyDel(addCount);private void addCount(int x){    x+=x;}
Add a method to a delegate type
requestHandler += addCount1;requestHandler += addCount2;//调用requestHandler(5);private void addCount1(int x){  }private void addCount2(int x){  }

? If a delegate type has a return value, the last method executes the return value that is the result

Anonymous methods are stored in the delegate method

? The function of the anonymous method in the delegate is to initialize the delegate, that is, the method in the method list is not a name.

MyDel requestHandler;requestHandler = delegate(int x){    x+=x;}
Anonymous method capture Variable

? It is also possible to know from here that the voice of an anonymous method should be the same as int y =5 ; or lower than its peers

MyDel requestHandler;int y=5;requestHandler = delegate(int x){    x=y+5;}
Delegate + Lamb expression
MyDel requestHandler;MyDel requestHandler1;//匿名方法requestHandler = delegate(int x) {x+20;}requestHandler1 =  x => {x+20;}
Event

? Associate with the Observer pattern, when a state triggers a method that triggers some object, the process is like a delegate invoking a list of methods, a Publisher is a delegate object, and a Subscriber is a list of methods in it. As with methods, properties, event events are members of a class or struct, so we cannot declare an event in an executable code, the initial value of the event is null

? Personal Understanding:

    • Event declarations are keywords for events, and methods, attributes, field-to-peer

    • When called, the event is called method

? for private delegates to events, note the following:

Directly on the code

delegate void CountDel();class Incrementer {  //事件本身就是个观察者,一旦被触发,就马上通知订阅者   public event CountDel  MyEvent;    //这是某个触发点  public void DoCount (){    for(int i =1;i<100;i++){      if(i%12==0 && MyEvent!=null){           MyEvent();      }    }  }}//订阅者class Dozens{   public int DozenCount {get;private set}  public void Dozens(Incrementer incrementer){       incrementer +=AddDozenCount;  }    public void AddDozenCount(){       DozenCount++;  }}class Test {   Incrementer inc = new Incrementer();   Dozens dozens = new Dozens(inc);   inc.DoCount();}
Standard event (EventHandler)

The standard events defined in the. NET environment are defined as follows:

public event delegate EventHandler (object sender , EventArgs args)

? From the formal parameter name you can see that the first parameter represents the sender, and the second parameter passes some information

To pass data by extending EventArgs

? You need to configure generic delegates to implement, on the code

//自定义EventArgsclass MyEventArgs : EventArgs{   public int Anum{     get;set;   }}class Incrementer {  //事件本身就是个观察者,一旦被触发,就马上通知订阅者   public event EventHandler<MyEventArgs>  MyEvent;    //这是某个触发点  public void DoCount (){    MyEventArgs eventArgs = new MyEventArgs();    for(int i =1;i<100;i++){      if(i%12==0 && MyEvent!=null){           eventArgs.Anum = i;           MyEvent(this,eventArgs);      }    }  }}//订阅者class Dozens{  public int DozenCount {get;private set}  public void Dozens(Incrementer incrementer){       incrementer +=AddDozenCount;  }    public void AddDozenCount(object obj,MyEventArgs e){       Console.writeLine("当数到{0}时,增加一",e.Anum);       DozenCount++;  }}class Test {   static void main (){      Incrementer inc = new Incrementer();      Dozens dozens = new Dozens(inc);      inc.DoCount();      Console.writeLine("共记录了{0}次",dozens.DozenCount);   }}
Asynchronous

? What is async? For example, you go to buy milk tea, the clerk said please wait, you in the clerk to make milk tea, you can brush friends circle, do other things, such as milk tea, you pay again, completed the purchase of milk tea this thing. For me, the staff is an asynchronous method of dispensing milk tea. Async is not necessarily performed on other threads, it may be executed on the same thread

? First look at the Async method

class Today{    async Task<Tea> MakeTeaAsync (){        Console.Writeline("开始做奶茶呀!");        Salewoman girl = new Salewomen();        Tea tea = await girl.makeTea();        return tea;     }}class Test {  public static void main(string args){        Today  to = new Today();        Task<Tea> teaTask = to.MakeTeaAsync();        Console.writeLine(teaTask.Tostring());  }    }

? The Async method has three return values, and void Task<T> gets the Task result call of the Async method Task.Result . The receive of the calling method is received with the Task object.

? If our async does not require asynchronous data, it can be executed all the time, but when the parallel thread needs asynchronous data, it still blocks waiting.

class Test{    public static void main (){         Task<int> task = CountAsync();                 ...         //下面需要用到异步的数据,那么加入异步没完成,此处会阻塞         Console.wrintLine("结果为: "+task.Result);              //异步方法另外两种返回值        Task task = CounterAsync1();        Task task = CounterAsync2();//或直接调用异步方法 CounterAsync();    }}private async Task<int> CountAsync(){   int result = await SocketHelper.get();   return result;}private async Task CountAsync1(){    int result = await SocketHelper.getAgain();    Console.writeLine("hello world !");}private async void CountAsync2(){    int result = await SocketHelper.getAgain1();}

? So, is there a solution? I just don't want to block it. There, callback. Introduction later

Async method executes on new thread

? Async is performed by default on the current thread, and when new threads are required to execute, use the lamb expression directly

private async Task<int> CountAsync(){     int result = await Task.Run(new Fun<int>(Get));   //lamb表达式,   int result1 = await Task.Run(()=>{       return SocketHelper.get(num);   });     return result;}private int GetCount(int num){    return SocketHelper.get(num);}

? Task.Run( )The returned results are Task of Task<TResult> two kinds, the classes used by the parameters have Action , Fun<TResult> and Fun<Task> , where Fun<Task> not spoken, the detailed methods are as follows, (learn two simple types)

public static Task Run (Action action) {}public static Task<TResult> Run (Func<TResult> func) {}

? Actionand Func<TResult> is two delegates, their method list signature is not required parameters , the return value one is void, the other is an incoming generic, the above example

//委托Action  public delegate void Action();//委托Func<TResult>public delegate TResult Func<out TResult>();//创建匿名委托对象(方法列表)内添加Get方法int result = await Task.Run(new Fun<int>(Get));

? If I need to perform a task that needs to pass parameters, you can write this

int reusult = await Task.Run(()=>Get(5,6));

? The above example ()=>Get(5,6) creates an Func<TResult> object and adds an anonymous method to the delegate (the list of methods) that executes within this anonymous method.Get(5,6)

Canceling a task in an async method

? The same is the Task.Run( ) method, which uses two classes, CancelationToken and, the CancelationTokenSource latter from the name can be seen to be generated CancelationToken , and use CancelationToken to cancel the task is actually CancelationToken the property of the IsCancelationRequestedtrue

public static Task Run (Action action , CancelationToken token) {}public static Task<TResult> Run (Func<TResult> func , CancelationToken token ) {}
例子
  class Test {public void main () {Cancelationtokensource Source = new Cancelationtokensource ();           Cancelationtoken tokent = Source.token;     MyClass my = new MyClass (); Task task = My.           CancelAsync (token);     Task.wait ();     Token.cancel;     Task.wait ();  Console.WriteLine ("End");     }}class MyClass {public async void CancelAsync (Cancelationtoken token) {if (iscancelationrequested) return;      Task task = await Task.run (new Fun (Testtask), token);     } public void Testtask () {Console.WriteLine ("Start");          for (int i = 0; i < 5; i++) {if (iscancelationrequested) {return;         } thread.sleep (1000);                 Console.WriteLine ("{0} of counts is completed", i+1); }  }} 
//带注释运行开始1 of counts is completed 2 of counts is completed3 of counts is completed4 of counts is completed 5 of counts is completed结束  //不带注释运行开始1 of counts is completed 2 of counts is completed3 of counts is completed结束
Handling Exceptions in Async

? awaitAdd the statement directlytry..catch

Wait for asynchronous to finish before continuing to run
//等待单个任务完成后继续执行Task.Wait()  //等待一组任务完成后Task[] tasks = new Task[]{t1,t2};Task.WaitAll(tasks);
Delegate Asynchronous programming

? When there is only one method in the delegate (as long as one method in the method list), this method can be executed asynchronously in another thread (thread in the thread pool), the method used is delegated BeginInvoke , and the BeginInvoke returned IAsyncResult Iscompleted property can be checked when you want to get to the asynchronous result. or call the delegate EndInvoke to wait for the asynchronous completion.

namespace common.been{Internal delegate int mydelegate (string milk, string tea); Class Test {private MyDelegate del = delegate (string milk, String tea) {Console.WriteLine (mi            LK + "" + tea); Return milk. Length + tea.        Length;        }; public void Mycallback (IAsyncResult asyncResult) {AsyncResult asynccallback = (asyncResult) asyncResult .            asyncstate;            MyDelegate calldelegate = (mydelegate) asynccallback.asyncdelegate;            int result = Calldelegate.endinvoke (AsyncResult);            Here are some other operations} public void Main () {string m = "cow milk";            String t = "black tea";            Public IAsyncResult BeginInvoke (string milk, String tea, AsyncCallback callback, Object State)//no callbacks are used IAsyncResult AsyncResult = Del.            BeginInvoke (m, t, NULL, NULL); int result = Del.            EndInvoke (AsyncResult); Public delegate VoiD AsyncCallback (IAsyncResult ar); Use callback IAsyncResult AsyncResult1 = Del.                    BeginInvoke (M, T, new AsyncCallback (Mycallback), Del); }    }}

? BeginInvokereturns an IAsyncResult object, which is actually an AsyhcResult object, what is their relationship like?

? Where a AsyncDelegate BeginInvoke delegate reference to the calling method is maintained, and the AsyncState BeginInvoke fourth parameter of the method is preserved.

Timer

? Periodic execution of the asynchronous class, also it is also from the line Cheng fetch thread execution method, and can pass in callback

class Test {    ///    ///第二个参数: 传给回调的对象引用    ///第三个参数: 多久后开始    ///第四个参数: 每过多久循环    public void main(){            //public Timer( TimerCallback callback, object state, int dueTime, int period)             //public delegate void TimerCallback(object state);            string giveCallback = "love you ";            Timer timer = new Timer(new TimerCallback(TimeCallback), giveCallback, 2000, 3000);          }      private void  TimeCallback(object obj)    {            string whatYouGive = (string) obj;    }}

C # Delegate, event, asynchronous

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.