2.5、Task.FromResult的应用
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static IDictionary<string, string> cache = new Dictionary<string, string>() { {"0001","A"}, {"0002","B"}, {"0003","C"}, {"0004","D"}, {"0005","E"}, {"0006","F"}, }; public static void Main() { Task<string> task = GetValueFromCache("0006"); Console.WriteLine("主程序继续执行。。。。"); string result = task.Result; Console.WriteLine("result={0}", result); } private static Task<string> GetValueFromCache(string key) { Console.WriteLine("GetValueFromCache开始执行。。。。"); string result = string.Empty; //Task.Delay(5000); Thread.Sleep(5000); Console.WriteLine("GetValueFromCache继续执行。。。。"); if (cache.TryGetValue(key, out result)) { return Task.FromResult(result); } return Task.FromResult(""); } } }
2.6、使用IProgress实现异步编程的进程通知
IProgress<in T>只提供了一个方法void Report(T value),通过Report方法把一个T类型的值报告给IProgress,然后IProgress<in T>的实现类Progress<in T>的构造函数接收类型为Action<T>的形参,通过这个委托让进度显示在UI界面中。
using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void DoProcessing(IProgress<int> progress) { for (int i = 0; i <= 100; ++i) { Thread.Sleep(100); if (progress != null) { progress.Report(i); } } } static async Task Display() { //当前线程 var progress = new Progress<int>(percent => { Console.Clear(); Console.Write("{0}%", percent); }); //线程池线程 await Task.Run(() => DoProcessing(progress)); Console.WriteLine(""); Console.WriteLine("结束"); } public static void Main() { Task task = Display(); task.Wait(); } } }
2.7、Factory.FromAsync的应用 (简APM模式(委托)转换为任务)(BeginXXX和EndXXX)
带回调方式的
using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { private delegate string AsynchronousTask(string threadName); private static string Test(string threadName) { Console.WriteLine("Starting..."); Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep(TimeSpan.FromSeconds(2)); Thread.CurrentThread.Name = threadName; return string.Format("Thread name: {0}", Thread.CurrentThread.Name); } private static void Callback(IAsyncResult ar) { Console.WriteLine("Starting a callback..."); Console.WriteLine("State passed to a callbak: {0}", ar.AsyncState); Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread); Console.WriteLine("Thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId); } //执行的流程是 先执行Test--->Callback--->task.ContinueWith static void Main(string[] args) { AsynchronousTask d = Test; Console.WriteLine("Option 1"); Task<string> task = Task<string>.Factory.FromAsync( d.BeginInvoke("AsyncTaskThread", Callback, "a delegate asynchronous call"), d.EndInvoke); task.ContinueWith(t => Console.WriteLine("Callback is finished, now running a continuation! Result: {0}", t.Result)); while (!task.IsCompleted) { Console.WriteLine(task.Status); Thread.Sleep(TimeSpan.FromSeconds(0.5)); } Console.WriteLine(task.Status); } } }
不带回调方式的
using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { private delegate string AsynchronousTask(string threadName); private static string Test(string threadName) { Console.WriteLine("Starting..."); Console.WriteLine("Is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread); Thread.Sleep(TimeSpan.FromSeconds(2)); Thread.CurrentThread.Name = threadName; return string.Format("Thread name: {0}", Thread.CurrentThread.Name); } //执行的流程是 先执行Test--->task.ContinueWith static void Main(string[] args) { AsynchronousTask d = Test; Task<string> task = Task<string>.Factory.FromAsync( d.BeginInvoke, d.EndInvoke, "AsyncTaskThread", "a delegate asynchronous call"); task.ContinueWith(t => Console.WriteLine("Task is completed, now running a continuation! Result: {0}", t.Result)); while (!task.IsCompleted) { Console.WriteLine(task.Status); Thread.Sleep(TimeSpan.FromSeconds(0.5)); } Console.WriteLine(task.Status); } } }