异步编程模型
Posted IT苦行僧-QF
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了异步编程模型相关的知识,希望对你有一定的参考价值。
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 async) { 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 => { return 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(); }
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(); }
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); } }
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); } }
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; } } }
以上是关于异步编程模型的主要内容,如果未能解决你的问题,请参考以下文章