. Net cancellable Task

Source: Internet
Author: User
Tags apm thread tostring

Overview

. NET based on the delegated APM (Asynchronous programming model) is used in combination of BeginInvoke, EndInvoke, and Asynccallback,iasyncresult, Allows programmers to easily make asynchronous calls, asynchronous callbacks, and synchronous wait operations. However, the. NET platform has not yet provided a secure and reliable mechanism for thread aborts (abort), perhaps because APM does not include a time-out mechanism for asynchronous invocations, but rather a potentially contentious task for the user to grasp.

As a supplement to the APM model, this article provides an asynchronous call timeout mechanism through the Cancellabletask class. The design of the Cancellabletask class has two main considerations:

1. Maintain APM style, users can still use familiar BeginInvoke, EndInvoke, IAsyncResult, AsyncCallback, etc.

2. Provides default timeout processing based on Thread.Abort, while supporting user-defined cancel callbacks.

Use

The Cancellabletask constructor contains the Workcallbak and cancelcallback (optional) two parameters, corresponding to the work callback and the cancel callback, respectively. Cancellabletask's BeginInvoke maintains the APM style and can be viewed as an extended version of the timeout parameter (unit: MS); The use of AsyncCallback and IAsyncResult is consistent with APM. The exception generated by the work delegate is thrown when EndInvoke, and EndInvoke throws a ThreadAbortException exception if the thread is aborted by timeout.

The following is an example of the use of a cancellabletask:

Class Program {static void Main (string[] args) {//default timeout direct abort thread {Console.WriteLine
            ("[Case 1]");
            Cancellabletask cancellabletask = new Cancellabletask (Work);
            state arg = new state {Loop =, Stop = false}; IAsyncResult asyncresult = Cancellabletask.begininvoke (ARG, AR => Console.WriteLine (
            "Async Callback")), NULL, 10 * 1000);
            AsyncResult.AsyncWaitHandle.WaitOne ();
                try {Object r = Cancellabletask.endinvoke (asyncresult);
            Console.WriteLine ("Return" + R);
            catch (ThreadAbortException) {Console.WriteLine ("Thread aborted"); The catch (Exception exp) {Console.WriteLine (exp.
            ToString ()); ///Custom Cancel callback {Console.WriteLine (ENVIronment.
            NewLine + "[Case 2]");
            Cancellabletask cancellabletask = new Cancellabletask (Work, Cancel);
            state arg = new state {Loop =, Stop = false};
                    IAsyncResult asyncresult = Cancellabletask.begininvoke (ARG, AR => {try {object r = Cancellabletask.endinvoke (
                            AR);
                        Console.WriteLine ("Return" + R); catch (ThreadAbortException) {Console.Write
                        Line ("Thread aborted"); catch (Exception exp) {Console.WriteLine (ex
                        P.tostring ());
        }), ARG, 10 * 1000);
    } console.readline (); } static Object Work (Object arg) {state ' = arg as State;
        int i; for (i = 0; i < state. Loop; i++) {if (state).
            Stop) break;
            Console.WriteLine (i);
        Thread.Sleep (1000);
    return i;
        The static void Cancel (object state) {State St. = state as State; St.
    Stop = true;
    } internal class state {public int Loop {get; set;} public bool Stop {get; set;}}

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.