. NET non-blocking event get returns asynchronous callback result

Source: Internet
Author: User

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;namespaceasynccallback_delegate{classProgram {Static voidMain (string[] args) {JobManager Manager=NewJobManager (); Readjob Read= Manager. Run<readjob>(); Read. Started+=NewEventHandler (read_started); Read.completed+=NewEventhandler<completedeventargs>(read_completed); Read. OnUnhandledException+=NewEventhandler<exceptioneventargs>(read_onunhandledexception); Read.            Execute ();  while(!read. iscompleted) {Console.WriteLine ("Main thread["+ Thread.CurrentThread.ManagedThreadId +"] is waiting to close ..."); Thread.Sleep ( -); } Console.WriteLine ("Readjob is completed and return value:"+read.            RetVal); Console.WriteLine ("Jobs has been finished, press any key to continue ...");        Console.readkey (); }        Static voidRead_onunhandledexception (Objectsender, Exceptioneventargs e) {Console.WriteLine ("Exception:"+ Sender. GetType (). FullName +"Exception Message:"+e.message); }        Static voidRead_completed (Objectsender, CompletedEventArgs e) {Console.WriteLine ("Completed:"+ Sender. GetType (). FullName +"Process executed Result:"+e.success); }        Static voidRead_started (Objectsender, EventArgs e) {Console.WriteLine ("Started:"+sender. GetType ().        FullName); }    }     Public classJobManager { PublicT run<t> ()whereT:ijobservice,New()        {            return NewT (); }    }     Public InterfaceIjobservice {voidExecute (); EventEventhandler<completedeventargs>completed; EventEventHandler Started; EventEventhandler<exceptioneventargs>onunhandledexception; }    Delegate voidProcessdelegate (stringmessage);  Public classReadjob:ijobservice {//Define events for Readjob instance objects to register externally         Public EventEventHandler Started;  Public EventEventhandler<completedeventargs>completed;  Public EventEventhandler<exceptioneventargs>onunhandledexception; ObjectLockobj =New Object(); EventEventhandler<completedeventargs>ijobservice.completed {add {Lock(lockobj) {completed+=value; }} remove {Lock(lockobj) {completed-=value; }            }        }        EventEventHandler ijobservice.started {add {Lock(lockobj) {Started+=value; }} remove {Lock(lockobj) {Started-=value; }            }        }        EventEventhandler<exceptioneventargs>Ijobservice.onunhandledexception {add {Lock(lockobj) {onunhandledexception+=value; }} remove {Lock(lockobj) {onunhandledexception-=value; }            }        }         Public BOOLiscompleted {Get;Set; }  Public BOOLRetVal {Get;Set; }  Public voidExecute () {iscompleted=false; RetVal=false; EventHandler EventHandler=Started; if(NULL!=EventHandler) {EventHandler ( This,NewEventArgs ()); }            //calling the Process method in asynchronous callback mode//The return value and the completed event are called in the callback methodProcessdelegate process =Process; Process. BeginInvoke ("Readjob", Completedmethod, process); }         Public voidProcess (String message) {Console.WriteLine ("Process thread["+ Thread.CurrentThread.ManagedThreadId +"]:"+ Message +"Jobservice:"+ This. GetType ().            FullName); Thread.Sleep ( -); //Test//throw new Exception ("Test Exception");        }        //method called after completion of asynchronous callback execution         Public voidCompletedmethod (IAsyncResult result) {//Get return value            Try{(result. AsyncState asprocessdelegate).                EndInvoke (result); RetVal=true; //thread synchronization uses temporary variables instead of EventHandler, and delegates are immutable immutable//You can also use Interlocked.compareexchange (ref eventhandler,null,null)Eventhandler<completedeventargs> EventHandler =completed; if(NULL!=EventHandler) {EventHandler ( This,NewCompletedEventArgs (true)); }            }            Catch(Exception ex) {//exception-handling events are executed again, thread synchronization uses temporary variables instead of EventHandler, and delegates are immutable immutable//You can also use Interlocked.compareexchange (ref eventhandler,null,null)eventhandler<exceptioneventargs> eh =onunhandledexception; if(NULL!=eh) {EH ( This,NewExceptioneventargs (ex.                Message)); } RetVal=false; }            //executes the completed event registration method, where the EventHandler temporary variable is used to avoid the event being removed if NULL is judged//If you need to use multithreadingIsCompleted =true; }    }     Public classCompletedeventargs:eventargs { Public BOOLSuccess {Get;Set; }  PublicCompletedEventArgs (BOOLsuccess) {             This. Success =success; }    }     Public classExceptioneventargs:eventargs { Public stringMessage {Get;Set; }  PublicExceptioneventargs (stringmessage) {             This. Message =message; }    }}

. NET non-blocking event get returns asynchronous callback result

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.