異步編程模型
阿新 • • 發佈:2018-06-07
KS c-c != exe eap erro enc key lse
class Program { static void Main(string[] args) { var func = new Func<string, string>(i => { return i + "i can fly"; }); var state = func.BeginInvoke("yes,", Callback, func); Console.Read(); } static void Callback(IAsyncResult asyncView Code) { var result = async.AsyncState as Func<string, string>; Console.WriteLine(result.EndInvoke(async)); } }
class Program { static void Main(string[] args) { var func = new Func<string, string>(i => {View Codereturn i + "i can fly"; }); Task<string>.Factory.FromAsync(func.BeginInvoke, func.EndInvoke, "yes,", null).ContinueWith (i => { Console.WriteLine(i.Result); }); Console.Read(); } }
static void Main(string[] args) { var path = "C://1.txt"; FileStream fs = new FileStream(path, FileMode.Open); FileInfo info = new FileInfo(path); byte[] b = new byte[info.Length]; var asycState = fs.BeginRead(b, 0, b.Length, (result) => { var file = result.AsyncState as FileStream; Console.WriteLine("文件內容:{0}", Encoding.Default.GetString(b)); file.Close(); }, fs); Console.WriteLine("我是主線程,我不會被阻塞!"); Console.Read(); }View Code
static void Main(string[] args) { var path = "C://1.txt"; FileStream fs = new FileStream(path, FileMode.Open); FileInfo info = new FileInfo(path); byte[] b = new byte[info.Length]; Task<int>.Factory.FromAsync(fs.BeginRead, fs.EndRead, b, 0, b.Length, null, TaskCreationOptions.None) .ContinueWith (i => { Console.WriteLine("文件內容:{0}", Encoding.Default.GetString(b)); }); Console.WriteLine("我是主線程,我不會被阻塞!"); Console.Read(); }View Code
class Program { static byte[] b; static void Main() { string[] array = { "C://1.txt", "C://2.txt", "C://3.txt" }; List<Task<string>> taskList = new List<Task<string>>(3); foreach (var item in array) { taskList.Add(ReadAsyc(item)); } Task.Factory.ContinueWhenAll(taskList.ToArray(), i => { string result = string.Empty; //獲取各個task返回的結果 foreach (var item in i) { result += item.Result; } //倒序 String content = new String(result.OrderByDescending(j => j).ToArray()); Console.WriteLine("倒序結果:"+content); }); Console.WriteLine("我是主線程,我不會被阻塞"); Console.ReadKey(); } //異步讀取 static Task<string> ReadAsyc(string path) { FileInfo info = new FileInfo(path); byte[] b = new byte[info.Length]; FileStream fs = new FileStream(path, FileMode.Open); Task<int> task = Task<int>.Factory.FromAsync(fs.BeginRead, fs.EndRead, b, 0, b.Length, null, TaskCreationOptions.None); //返回當前task的執行結果 return task.ContinueWith(i => { return i.Result > 0 ? Encoding.Default.GetString(b) : string.Empty; }, TaskContinuationOptions.ExecuteSynchronously); } }View Code
class Program { static void Main(string[] args) { WebClient client = new WebClient(); client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadFileAsync(new Uri("http://imgsrc.baidu.com/baike/abpic/item/6a600c338744ebf844a0bc74d9f9d72a6159a7ac.jpg"), "1.jpg", "圖片下完了,你懂的!"); Console.WriteLine("我是主線程,我不會被阻塞!"); Console.Read(); } static void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { Console.WriteLine("\n" + e.UserState); } }View Code
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading.Tasks; using System.Net; using System.ComponentModel; namespace ConsoleApplication4 { class Program { static void Main() { var downloadTask = DownLoadFileInTask( new Uri(@"http://www.7720mm.cn/uploadfile/2010/1120/20101120073035736.jpg") , "C://1.jpg"); downloadTask.ContinueWith(i => { Console.WriteLine("圖片:" + i.Result + "下載完畢!"); }); Console.WriteLine("我是主線程,我不會被阻塞!"); Console.Read(); } static Task<string> DownLoadFileInTask(Uri address, string saveFile) { var wc = new WebClient(); var tcs = new TaskCompletionSource<string>(address); //處理異步操作的一個委托 AsyncCompletedEventHandler handler = null; handler = (sender, e) => { if (e.Error != null) { tcs.TrySetException(e.Error); } else { if (e.Cancelled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(saveFile); } } wc.DownloadFileCompleted -= handler; }; //我們將下載事件與我們自定義的handler進行了關聯 wc.DownloadFileCompleted += handler; try { wc.DownloadFileAsync(address, saveFile); } catch (Exception ex) { wc.DownloadFileCompleted -= handler; tcs.TrySetException(ex); } return tcs.Task; } } }View Code
異步編程模型