c# task添加顺序_C# Task详解

1、Task的优势

ThreadPool相比Thread来说具备了很多优势,但是ThreadPool却又存在一些使用上的不方便。比如:

◆ ThreadPool不支持线程的取消、完成、失败通知等交互性操作;

◆ ThreadPool不支持线程执行的先后次序;

以往,如果开发者要实现上述功能,需要完成很多额外的工作,现在,FCL中提供了一个功能更强大的概念:Task。Task在线程池的基础上进行了优化,并提供了更多的API。在FCL4.0中,如果我们要编写多线程程序,Task显然已经优于传统的方式。

以下是一个简单的任务示例:

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{static void Main(string[] args)

{

Task t= new Task(() =>{

Console.WriteLine("任务开始工作……");//模拟工作过程

Thread.Sleep(5000);

});

t.Start();

t.ContinueWith((task)=>{

Console.WriteLine("任务完成,完成时候的状态为:");

Console.WriteLine("IsCanceled={0}\tIsCompleted={1}\tIsFaulted={2}", task.IsCanceled, task.IsCompleted, task.IsFaulted);

});

Console.ReadKey();

}

}

}

View Code

2、Task的用法

2.1、创建任务

(一)无返回值的方式

方式1:

var t1 = new Task(() => TaskMethod("Task 1"));

t1.Start();

Task.WaitAll(t1);//等待所有任务结束

注:任务的状态:

Start之前为:Created

Start之后为:WaitingToRun

方式2:

Task.Run(() => TaskMethod("Task 2"));

方式3:

Task.Factory.StartNew(() => TaskMethod("Task 3")); 直接异步的方法//或者

var t3=Task.Factory.StartNew(() => TaskMethod("Task 3"));

Task.WaitAll(t3);//等待所有任务结束//任务的状态:

Start之前为:Running

Start之后为:Running

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{static void Main(string[] args)

{var t1 = new Task(() => TaskMethod("Task 1"));var t2 = new Task(() => TaskMethod("Task 2"));

t2.Start();

t1.Start();

Task.WaitAll(t1, t2);

Task.Run(()=> TaskMethod("Task 3"));

Task.Factory.StartNew(()=> TaskMethod("Task 4"));//标记为长时间运行任务,则任务不会使用线程池,而在单独的线程中运行。

Task.Factory.StartNew(() => TaskMethod("Task 5"), TaskCreationOptions.LongRunning);#region 常规的使用方式Console.WriteLine("主线程执行业务处理.");//创建任务

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();

Console.WriteLine("主线程执行其他处理");

task.Wait();#endregionThread.Sleep(TimeSpan.FromSeconds(1));

Console.ReadLine();

}static void TaskMethod(stringname)

{

Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",

name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

}

}

}

View Code

async/await的实现方式:

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{async static voidAsyncFunction()

{await Task.Delay(1);

Console.WriteLine("使用System.Threading.Tasks.Task执行异步操作.");for (int i = 0; i < 10; i++)

{

Console.WriteLine(string.Format("AsyncFunction:i={0}", i));

}

}public static voidMain()

{

Console.WriteLine("主线程执行业务处理.");

AsyncFunction();

Console.WriteLine("主线程执行其他处理");for (int i = 0; i < 10; i++)

{

Console.WriteLine(string.Format("Main:i={0}", i));

}

Console.ReadLine();

}

}

}

View Code

(二)带返回值的方式

方式4:

Task task = CreateTask("Task 1");

task.Start();int result = task.Result;

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{static Task CreateTask(stringname)

{return new Task(() =>TaskMethod(name));

}static void Main(string[] args)

{

TaskMethod("Main Thread Task");

Task task = CreateTask("Task 1");

task.Start();int result =task.Result;

Console.WriteLine("Task 1 Result is: {0}", result);

task= CreateTask("Task 2");//该任务会运行在主线程中

task.RunSynchronously();

result=task.Result;

Console.WriteLine("Task 2 Result is: {0}", result);

task= CreateTask("Task 3");

Console.WriteLine(task.Status);

task.Start();while (!task.IsCompleted)

{

Console.WriteLine(task.Status);

Thread.Sleep(TimeSpan.FromSeconds(0.5));

}

Console.WriteLine(task.Status);

result=task.Result;

Console.WriteLine("Task 3 Result is: {0}", result);#region 常规使用方式

//创建任务

Task getsumtask = new Task(() =>Getsum());//启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)

getsumtask.Start();

Console.WriteLine("主线程执行其他处理");//等待任务的完成执行过程。

getsumtask.Wait();//获得任务的执行结果

Console.WriteLine("任务执行结果:{0}", getsumtask.Result.ToString());#endregion}static int TaskMethod(stringname)

{

Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",

name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

Thread.Sleep(TimeSpan.FromSeconds(2));return 42;

}static intGetsum()

{int sum = 0;

Console.WriteLine("使用Task执行异步操作.");for (int i = 0; i < 100; i++)

{

sum+=i;

}returnsum;

}

}

}

View Code

async/await的实现:

usingSystem;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{public static voidMain()

{var ret1 =AsyncGetsum();

Console.WriteLine("主线程执行其他处理");for (int i = 1; i <= 3; i++)

Console.WriteLine("Call Main()");int result = ret1.Result; //阻塞主线程

Console.WriteLine("任务执行结果:{0}", result);

}async static TaskAsyncGetsum()

{await Task.Delay(1);int sum = 0;

Console.WriteLine("使用Task执行异步操作.");for (int i = 0; i < 100; i++)

{

sum+=i;

}returnsum;

}

}

}

View Code

2.2、组合任务.ContinueWith

简单Demo:

usingSystem;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{public static voidMain()

{//创建一个任务

Task task = new Task(() =>{int sum = 0;

Console.WriteLine("使用Task执行异步操作.");for (int i = 0; i < 100; i++)

{

sum+=i;

}returnsum;

});//启动任务,并安排到当前任务队列线程中执行任务(System.Threading.Tasks.TaskScheduler)

task.Start();

Console.WriteLine("主线程执行其他处理");//任务完成时执行处理。

Task cwt = task.ContinueWith(t =>{

Console.WriteLine("任务完成后的执行结果:{0}", t.Result.ToString());

});

task.Wait();

cwt.Wait();

}

}

}

View Code

任务的串行:

usingSystem;usingSystem.Collections.Concurrent;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{static void Main(string[] args)

{

ConcurrentStack stack = new ConcurrentStack();//t1先串行

var t1 = Task.Factory.StartNew(() =>{

stack.Push(1);

stack.Push(2);

});//t2,t3并行执行

var t2 = t1.ContinueWith(t =>{intresult;

stack.TryPop(outresult);

Console.WriteLine("Task t2 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);

});//t2,t3并行执行

var t3 = t1.ContinueWith(t =>{intresult;

stack.TryPop(outresult);

Console.WriteLine("Task t3 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);

});//等待t2和t3执行完

Task.WaitAll(t2, t3);//t7串行执行

var t4 = Task.Factory.StartNew(() =>{

Console.WriteLine("当前集合元素个数:{0},Thread id {1}", stack.Count, Thread.CurrentThread.ManagedThreadId);

});

t4.Wait();

}

}

}

View Code

子任务:

usingSystem;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{public static voidMain()

{

Task parent = new Task(state =>{

Console.WriteLine(state);string[] result = new string[2];//创建并启动子任务

new Task(() => { result[0] = "我是子任务1。"; }, TaskCreationOptions.AttachedToParent).Start();new Task(() => { result[1] = "我是子任务2。"; }, TaskCreationOptions.AttachedToParent).Start();returnresult;

},"我是父任务,并在我的处理过程中创建多个子任务,所有子任务完成以后我才会结束执行。");//任务处理完成后执行的操作

parent.ContinueWith(t =>{

Array.ForEach(t.Result, r=>Console.WriteLine(r));

});//启动父任务

parent.Start();//等待任务结束 Wait只能等待父线程结束,没办法等到父线程的ContinueWith结束//parent.Wait();

Console.ReadLine();

}

}

}

View Code

动态并行(TaskCreationOptions.AttachedToParent) 父任务等待所有子任务完成后 整个任务才算完成

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classNode

{public Node Left { get; set; }public Node Right { get; set; }public string Text { get; set; }

}classProgram

{staticNode GetNode()

{

Node root= newNode

{

Left= newNode

{

Left= newNode

{

Text= "L-L"},

Right= newNode

{

Text= "L-R"},

Text= "L"},

Right= newNode

{

Left= newNode

{

Text= "R-L"},

Right= newNode

{

Text= "R-R"},

Text= "R"},

Text= "Root"};returnroot;

}static void Main(string[] args)

{

Node root=GetNode();

DisplayTree(root);

}static voidDisplayTree(Node root)

{var task = Task.Factory.StartNew(() =>DisplayNode(root),

CancellationToken.None,

TaskCreationOptions.None,

TaskScheduler.Default);

task.Wait();

}static voidDisplayNode(Node current)

{if (current.Left != null)

Task.Factory.StartNew(()=>DisplayNode(current.Left),

CancellationToken.None,

TaskCreationOptions.AttachedToParent,

TaskScheduler.Default);if (current.Right != null)

Task.Factory.StartNew(()=>DisplayNode(current.Right),

CancellationToken.None,

TaskCreationOptions.AttachedToParent,

TaskScheduler.Default);

Console.WriteLine("当前节点的值为{0};处理的ThreadId={1}", current.Text, Thread.CurrentThread.ManagedThreadId);

}

}

}

View Code

2.3、取消任务 CancellationTokenSource

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{private static int TaskMethod(string name, intseconds, CancellationToken token)

{

Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",

name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);for (int i = 0; i < seconds; i++)

{

Thread.Sleep(TimeSpan.FromSeconds(1));if (token.IsCancellationRequested) return -1;

}return 42 *seconds;

}private static void Main(string[] args)

{var cts = newCancellationTokenSource();var longTask = new Task(() => TaskMethod("Task 1", 10, cts.Token), cts.Token);

Console.WriteLine(longTask.Status);

cts.Cancel();

Console.WriteLine(longTask.Status);

Console.WriteLine("First task has been cancelled before execution");

cts= newCancellationTokenSource();

longTask= new Task(() => TaskMethod("Task 2", 10, cts.Token), cts.Token);

longTask.Start();for (int i = 0; i < 5; i++)

{

Thread.Sleep(TimeSpan.FromSeconds(0.5));

Console.WriteLine(longTask.Status);

}

cts.Cancel();for (int i = 0; i < 5; i++)

{

Thread.Sleep(TimeSpan.FromSeconds(0.5));

Console.WriteLine(longTask.Status);

}

Console.WriteLine("A task has been completed with result {0}.", longTask.Result);

}

}

}

View Code

2.4、处理任务中的异常

单个任务:

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{static int TaskMethod(string name, intseconds)

{

Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",

name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

Thread.Sleep(TimeSpan.FromSeconds(seconds));throw new Exception("Boom!");return 42 *seconds;

}static void Main(string[] args)

{try{

Task task = Task.Run(() => TaskMethod("Task 2", 2));int result =task.GetAwaiter().GetResult();

Console.WriteLine("Result: {0}", result);

}catch(Exception ex)

{

Console.WriteLine("Task 2 Exception caught: {0}", ex.Message);

}

Console.WriteLine("----------------------------------------------");

Console.WriteLine();

}

}

}

View Code

多个任务:

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{static int TaskMethod(string name, intseconds)

{

Console.WriteLine("Task {0} is running on a thread id {1}. Is thread pool thread: {2}",

name, Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsThreadPoolThread);

Thread.Sleep(TimeSpan.FromSeconds(seconds));throw new Exception(string.Format("Task {0} Boom!", name));return 42 *seconds;

}public static void Main(string[] args)

{try{var t1 = new Task(() => TaskMethod("Task 3", 3));var t2 = new Task(() => TaskMethod("Task 4", 2));var complexTask =Task.WhenAll(t1, t2);var exceptionHandler = complexTask.ContinueWith(t =>Console.WriteLine("Result: {0}", t.Result),

TaskContinuationOptions.OnlyOnFaulted

);

t1.Start();

t2.Start();

Task.WaitAll(t1, t2);

}catch(AggregateException ex)

{

ex.Handle(exception=>{

Console.WriteLine(exception.Message);return true;

});

}

}

}

}

View Code

async/await的方式:

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{static asyncTask ThrowNotImplementedExceptionAsync()

{throw newNotImplementedException();

}static asyncTask ThrowInvalidOperationExceptionAsync()

{throw newInvalidOperationException();

}static asyncTask Normal()

{awaitFun();

}staticTask Fun()

{return Task.Run(() =>{for (int i = 1; i <= 10; i++)

{

Console.WriteLine("i={0}", i);

Thread.Sleep(200);

}

});

}static asyncTask ObserveOneExceptionAsync()

{var task1 =ThrowNotImplementedExceptionAsync();var task2 =ThrowInvalidOperationExceptionAsync();var task3 =Normal();try{//异步的方式

Task allTasks =Task.WhenAll(task1, task2, task3);awaitallTasks;//同步的方式//Task.WaitAll(task1, task2, task3);

}catch(NotImplementedException ex)

{

Console.WriteLine("task1 任务报错!");

}catch(InvalidOperationException ex)

{

Console.WriteLine("task2 任务报错!");

}catch(Exception ex)

{

Console.WriteLine("任务报错!");

}

}public static voidMain()

{

Task task=ObserveOneExceptionAsync();

Console.WriteLine("主线程继续运行........");

task.Wait();

}

}

}

View Code

2.5、Task.FromResult的应用

usingSystem;usingSystem.Collections.Generic;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{static IDictionary cache = new Dictionary()

{

{"0001","A"},

{"0002","B"},

{"0003","C"},

{"0004","D"},

{"0005","E"},

{"0006","F"},

};public static voidMain()

{

Task task = GetValueFromCache("0006");

Console.WriteLine("主程序继续执行。。。。");string result =task.Result;

Console.WriteLine("result={0}", result);

}private static Task GetValueFromCache(stringkey)

{

Console.WriteLine("GetValueFromCache开始执行。。。。");string result = string.Empty;//Task.Delay(5000);

Thread.Sleep(5000);

Console.WriteLine("GetValueFromCache继续执行。。。。");if (cache.TryGetValue(key, outresult))

{returnTask.FromResult(result);

}return Task.FromResult("");

}

}

}

View Code

2.6、使用IProgress实现异步编程的进程通知

IProgress只提供了一个方法void Report(T value),通过Report方法把一个T类型的值报告给IProgress,然后IProgress的实现类Progress的构造函数接收类型为Action的形参,通过这个委托让进度显示在UI界面中。

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{static void DoProcessing(IProgressprogress)

{for (int i = 0; i <= 100; ++i)

{

Thread.Sleep(100);if (progress != null)

{

progress.Report(i);

}

}

}static asyncTask Display()

{//当前线程

var progress = new Progress(percent =>{

Console.Clear();

Console.Write("{0}%", percent);

});//线程池线程

await Task.Run(() =>DoProcessing(progress));

Console.WriteLine("");

Console.WriteLine("结束");

}public static voidMain()

{

Task task=Display();

task.Wait();

}

}

}

View Code

2.7、Factory.FromAsync的应用 (简APM模式(委托)转换为任务)(BeginXXX和EndXXX)

带回调方式的

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{private delegate string AsynchronousTask(stringthreadName);private static string Test(stringthreadName)

{

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 voidCallback(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 task = Task.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);

}

}

}

View Code

不带回调方式的

usingSystem;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceConsoleApp1

{classProgram

{private delegate string AsynchronousTask(stringthreadName);private static string Test(stringthreadName)

{

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 task = Task.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);

}

}

}

View Code

//Task启动带参数和返回值的函数任务//下面的例子test2 是个带参数和返回值的函数。

private int test2(objecti)

{this.Invoke(new Action(() =>{

pictureBox1.Visible= true;

}));

System.Threading.Thread.Sleep(3000);

MessageBox.Show("hello:" +i);this.Invoke(new Action(() =>{

pictureBox1.Visible= false;

}));return 0;

}//测试调用

private voidcall()

{//Func funcOne = delegate(string s){ return "fff"; };

object i = 55;var t = Task.Factory.StartNew(new Func(test2), i);

}//= 下载网站源文件例子 == == == == == == == == == == == ==//HttpClient 引用System.Net.Http

private async Task< int> test2(objecti)

{this.Invoke(new Action(() =>{

pictureBox1.Visible= true;

}));

HttpClient client= newHttpClient();var a = await client.GetAsync("http://www.baidu.com");

Task s =a.Content.ReadAsStringAsync();

MessageBox.Show (s.Result);//System.Threading.Thread.Sleep(3000);//MessageBox.Show("hello:"+ i);

this.Invoke(new Action(() =>{

pictureBox1.Visible= false;

}));return 0;

}async private voidcall()

{//Func funcOne = delegate(string s){ return "fff"; };

object i = 55;var t = Task>.Factory.StartNew(new Func>(test2), i);

}//----------或者----------

private async voidtest2()

{this.Invoke(new Action(() =>{

pictureBox1.Visible= true;

}));

HttpClient client= newHttpClient();var a = await client.GetAsync("http://www.baidu.com");

Task s =a.Content.ReadAsStringAsync();

MessageBox.Show (s.Result);this.Invoke(new Action(() =>{

pictureBox1.Visible= false;

}));

}private voidcall()

{var t = Task.Run(newAction(test2));//相当于//Thread th= new Thread(new ThreadStart(test2));//th.Start();

}

Task启动带参数和返回值的函数任务

你可能感兴趣的:(c#,task添加顺序)