异步调用


.NET中提供的异步操作,对于开发搞系统性能开发有非常重要的意义,常用场合:

一、常用应用范围

1、文件 IO、流 IO、套接字 IO

2、网络

3、远程处理信道(HTTP、TCP)和代理

4、使用 ASP.NET 创建的 XML Web services

5、使用 MessageQueue 类的消息队列

二、常用方法 

1、代理类: 

BeginInvoke:开始异步操作

AsyncCallback:回调函数申明

EndInvoke:等待只带异步操作结束

AsyncWaitHandle.WaitOne():阻塞当前进程,直到异步操作完成 

代理类申明:

public delegate string TestDelegate(int i);

处理方法申明:

        public string Test(int i)
        {
            Console.WriteLine(i.ToString());
            return i.ToString();
        }

回调函数申明:

        static void CallbackMethod(IAsyncResult ar)
        {
            Console.WriteLine("call bakck");
        }

使用:

TestDelegate caller = new TestDelegate(new Program().Test);
            IAsyncResult result = caller.BeginInvoke(10, new AsyncCallback(CallbackMethod),null);


2、实现接口System.IAsyncResult

异步操作自己用多线程实现,而开始、结束、等待、完成等方法出发使用接口System.IAsyncResult实现

实现接口:

    public class MyAsyncResult : System.IAsyncResult
    {
        public object AsyncState
        {
            get;
            set;
        }

        System.Threading.WaitHandle asyncWaitHandle = new AutoResetEvent(false);

        public System.Threading.WaitHandle AsyncWaitHandle
        {
            get { return asyncWaitHandle; }
        }

        public bool CompletedSynchronously
        {
            get;
            set;
        }

        public bool IsCompleted
        {
            get;
            set;
        }

        int _myValue;
        public int myValue
        {
            set
            { _myValue = value; }
            get
            {
                // if (IsCompleted) 
                {
                    return _myValue;
                }
            }
        }
    }

定义处理方法以及call back方法:

        AsyncCallback asyncCallback;
        MyAsyncResult asyncResult;

        public TestAsync()
        {
            asyncCallback = new AsyncCallback(callback);
            asyncResult = new MyAsyncResult();
        }

        void callback(IAsyncResult asyncResult)
        {
            MyAsyncResult temp = asyncResult as MyAsyncResult;
            ((AutoResetEvent)temp.AsyncWaitHandle).Set();
        }


        public MyAsyncResult myAsyncMethod(int value, object asyncState)
        {

            Console.WriteLine("run myAsyncMethod");
            this.asyncResult.AsyncState = asyncState;
            this.asyncResult.myValue = value;
            Thread t = new Thread(new ThreadStart(myThread));//一个进程可以创建一个或多个线程以执行与该进程关联的部分程序代码
            t.Start();
            return this.asyncResult;
        }

调用:

        private static void fun3()
        {
            TestAsync obj = new TestAsync();
            MyAsyncResult r = obj.myAsyncMethod(100, null);
            r.AsyncWaitHandle.WaitOne();
            System.Console.WriteLine(r.myValue);
            System.Console.WriteLine("完成");
            System.Console.Read();
        }

3、对于不需要运行后返回的任务可以用线程池以及线程编程


4、Task 并行任务库

引人了一个的任务(System.Threading.Tasks命名空间的类型)机制来解决异步操作完成时间和完成后返回值的问题

Task task = new Task(() => {
                   Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");
                  for (int i = 0; i < 10; i++)
                    {
                       Console.WriteLine(i);
                  }
              });
              //启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)
               task.Start();

task.Start();   //任务开始
task.Wait();    //任务结束

//等待所有任务完成  
public static void WaitAll(params Task[] tasks);
//等待任意一个任务完成
public static int WaitAny(params Task[] tasks);
使用ContinueWith方法在任务完成时启动一个新任务

 Task cwt = task.ContinueWith(t => { 
                  Console.WriteLine("任务完成后的执行结果:{0}", t.Result.ToString()); 
              });
父子任务: 所有子任务全部完成以后父任务才会结束操作

任务调度:TaskScheduler 

5、异步任务处理类:PageAsyncTask

PageAsyncTask类包含对注册到页面的异步任务的管理,能够通过编程的方式在页面呈现前执行多个任务,还可以指定这些任务的运行模式是并行还是串行。任务的运行期在页面的PreRender事件和PreRenderComplete事件之间。

    protected void Page_Load(object sender, EventArgs e)
    {
        this.AsyncTimeout = TimeSpan.FromSeconds(30);
        PageAsyncTask pat = new PageAsyncTask(BeginAsync, EndAsync, TimeoutAsync, null, true);
        RegisterAsyncTask(pat);
    }

相关的相应参数:

    private IAsyncResult BeginAsync(object sender, EventArgs e, AsyncCallback cb, object state)
    {
        TerraService terra = new TerraService();
        Place place = new Place();
        place.City = "Seattle";
        place.State = "WA";
        place.Country = "US";
        IAsyncResult ar = terra.BeginGetPlaceFacts(place, cb, terra);
        return ar;
    }

    private void EndAsync(IAsyncResult ar)
    {
        TerraService terra = (TerraService)ar.AsyncState;
        PlaceFacts facts = terra.EndGetPlaceFacts(ar);
        this.LA.Text = String.Format("Latitude: {0:0.##}", facts.Center.Lat);
        this.LO.Text = String.Format("Longitude: {0:0.##}", facts.Center.Lon);
    }

    private void TimeoutAsync(IAsyncResult ar)
    {
        this.LA.Text = "Web service call timed out.";
    }




你可能感兴趣的:(异步调用)