c#异步实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;

namespace ConsoleApp5
{
    
    //


    /// 定义一个委托类型
    ///

    public delegate string Del();
    ///
    /// 异步编程实现类(主线程不会阻塞)
    ///

    public class AsynCallbackClass
    {
        public static string result;

        public static void Main(string[] args)
        {
            Del del = new Del(TaskClass.SleepTask);
            //开始执行异步操作,TaskClass.SleepTask无参数,Callback为定义的回调方法.
            for (int i = 0; i < 2; i++)
            {
                del.BeginInvoke(Callback, null);
            }
        
            Console.ReadLine();
        }

        ///


        /// 回调方法
        ///

        ///
        public static void Callback(IAsyncResult ar)
        {
            AsyncResult asyncResult = ar as AsyncResult;

            if (asyncResult == null) { return; }

            Del del = asyncResult.AsyncDelegate as Del;

            if (del == null) { return; }

            Console.WriteLine("回调方法中调用EndInvoke()方法,获取异步任务结果.\n", Thread.CurrentThread.ManagedThreadId);

            //结束执行异步操作,并返回异步任务结果.
            result = del.EndInvoke(ar);
            Console.WriteLine(result);
        }
    }

    ///


    /// 任务类
    ///

    public class TaskClass
    {
        public static string SleepTask()
        {
            Thread.Sleep(5000);
            return "异步线程执行成功.\n" + "---" + DateTime.Now.ToString();
        }
    }
}
 

你可能感兴趣的:(ASP.NET)