多線程編程模型APM 、EAM、TAP

C#7.0編程

一、異步編程模式APM

相似xxxBegin,xxxEnd 一對方法委託線程池執行異步

 Func<int> b = new Func<int>(() =>
            {
                return 10;
            });

            b.BeginInvoke(x =>
            {
                int r = b.EndInvoke(x);
            }, null);

其餘例如FileStream.ReadBegin,ReadEnd等異步編程

fs.BeginRead(bytes, 0, bytes.Length, ar =>
{
    var r = fs.EndRead(ar);
Console.WriteLine(r);

}, null);

  

二、基於事件的編程模型(EAP)

相似xxxAsync 線程

 WebClient client = new WebClient();
            Uri uri = new Uri("http://www.baidu.com");
            client.DownloadDataCompleted += (sender, e) =>
            {
                byte[] bytes = e.Result;
            };
            client.DownloadDataAsync(new Uri("http://www.baidu.com"));

  

三、基於Task的編程模型(TAP)

APM和EAP都能包裝成Task使用(微軟推薦使用Task)blog

以下使用Task.Factory.FromAsync()包裝APM爲TAP事件

 Action a = new Action(() =>
            {
                Console.WriteLine("hello");
            });
           
            Task.Factory.FromAsync(a.BeginInvoke, a.EndInvoke, string.Empty);

  

 string path = Environment.CurrentDirectory + "/2.txt";

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                Task<int> t = Task.Factory.FromAsync(fs.BeginRead, fs.EndRead, bytes, 0, bytes.Length, null);
                Console.WriteLine(t.Result);
            }

以下使用TaskCompletionSource包裝EAP爲TAPstring

public static Task<int> DoS()
        {
            TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>();

            WebClient client = new WebClient();

            client.DownloadDataAsync(new Uri("http://www.baidu.com"));
            client.DownloadStringCompleted += (sender, e) =>
            {
                try
                {
                    taskCompletionSource.TrySetResult(e.Result.Length);
                }
                catch (Exception ex)
                {
                    taskCompletionSource.TrySetException(ex);
                }
            };

            client.DownloadDataAsync(new Uri("http://www.baidu.com"));
            return taskCompletionSource.Task;
        }

  如下方法內部也是使用TaskCompletionSourceit

Task<byte[]> Task = client.DownloadDataTaskAsync(uri);
相關文章
相關標籤/搜索