C#-Task的各种⽤法和详解
1、Task简介【*所有的线程任务都会随着主线程的退出⽽退出】
ThreadPool相⽐Thread来说具备了很多优势,但是ThreadPool却⼜存在⼀些使⽤上的不⽅便。⽐如:
ThreadPool不⽀持线程的取消、完成、失败通知等交互性操作;
ThreadPool不⽀持线程执⾏的先后次序;
以往,如果开发者要实现上述功能,需要完成很多额外的⼯作,现在,FCL中提供了⼀个功能更强⼤的概念:Task。Task在线程池的基础上进⾏了优化,并提供了更多的
API。在FCL4.0中,如果我们要编写多线程程序,Task显然已经优于传统的⽅式。
以下是⼀个简单的任务⽰例:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Task1
{
public void TaskMethod1()
{
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);
});
}
}
}
2、Task⽤法【new只是创建了⼀个任务,需要Start才会执⾏,Task.Run是直接开始执⾏】
2.1创建任务
不带返回参数的
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Task2
{
public void TaskMethod1(string param)
{
Console.WriteLine($"输⼊参数:{param}");
}
public void TaskMethod2()
{
//⽅式1
var t1 = new Task(() => TaskMethod1("⽆返回值⽅式1.1"));
var t2 = new Task(() => TaskMethod1("⽆返回值⽅式1.2"));
t1.Start();
t2.Start();
Task.WaitAll(t1, t2);//会等待所有任务结束,主线程才会退出
//⽅式2
await和async使用方法Task.Run(() => TaskMethod1("⽆返回值⽅式2"));
/
/⽅式3
Task.Factory.StartNew(() => TaskMethod1("⽆返回值⽅式3"));//异步⽅法
//or
Task t3 = Task.Factory.StartNew(() => TaskMethod1("⽆返回值⽅式3"));
t3.Wait();
}
}
}
async/await的实现⽅式
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Task2
{
/// <summary>
/// async/await的实现⽅式:
/// </summary>
public async void TaskMethod3()
{
//Task.Delay⽅法只会延缓异步⽅法中后续部分执⾏时间,当程序执⾏到await表达时,⼀⽅⾯会⽴即
返回调⽤⽅法,执⾏调⽤⽅法中的剩余部分,这⼀部分程序的执⾏不会延长。另⼀⽅⾯根据Delay()⽅法中的参数,延时对异步⽅法中后续部 await Task.Delay(1000);
Console.WriteLine("执⾏异步⽅法");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
}
}
using System;
namespace ThreadStudy
{
class Program
{
static void Main(string[] args)
{
//Task1 task1 = new Task1();
//task1.TaskMethod1();
Task2 task2 = new Task2();
Console.WriteLine("主线程执⾏其他任务...");
task2.TaskMethod3();
Console.WriteLine("主线程执⾏其他处理...");
for (int i = 0; i < 10; i++)
{
Console.WriteLine("主线程{i}");
}
Console.ReadKey();
}
}
}
带返回值得⽅式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
public class Task3
{
int TestMethod1()
{
Console.WriteLine("测试⽅法");
Thread.Sleep(2000);
return 12;
}
public Task<int> TaskMethod1()
{
return Task.Run(() => TestMethod1());//Task<int>.Run(() => TestMethod1()); 简化了<int> }
public int TestMethod2()
{
int sum = 0;
Console.WriteLine("执⾏异步操作");
for (int i = 0; i < 100; i++)
{
sum += i;
}
Thread.Sleep(1000);
return sum;
}
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Program
{
static void Main(string[] args)
{
//⽅式1
Task3 task3 = new Task3();
Task<int> task = task3.TaskMethod1();
int result = task.Result;//⽅法执⾏完,主线程才会结束
Console.WriteLine($"1 = {result}");
/
/⽅式2
task = task3.TaskMethod1();
Console.WriteLine(task.Status);
while (!task.IsCompleted)
{
Console.WriteLine(task.Status);
Thread.Sleep(200);
}
Console.WriteLine(task.Status);
result = task.Result;
Console.WriteLine($"2 = {result}");
/
/⽅式3
Task<int> task2 = Task.Run(() => task3.TestMethod2());
Console.WriteLine("主线程执⾏其他操作");
//task2.Wait();Result为必须执⾏完,主线程才结束,所以这⾥不写Wait不影响
Console.WriteLine($"3 = {task2.Result}");
}
}
}
async/await⽅式
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Program
{
static void Main(string[] args)
{
var task = AsyncMethod1();
Console.WriteLine("主线程执⾏其他处理");
for (int i = 0; i < 3; i++)
{
Console.WriteLine($"Main{i}");
}
int result = task.Result;
Console.WriteLine(result);
}
async static Task<int> AsyncMethod1()
{
await Task.Delay(1000);//⽴刻返回执⾏调⽤⽅法的后续部分,延迟1秒之后后⾯的部分
int sum = 0;
Console.WriteLine("使⽤Task执⾏异步操作.");
for (int i = 0; i < 1000; i++)
{
sum += i;
}
return sum;
}
}
}
2.2组合任务ContinueWith
简单demo
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Program
{
static void Main(string[] args)
{
Task<int> task = new Task<int>(() =>
{
int sum = 0;
Console.WriteLine("任务1");
for (int i = 0; i < 100; i++)
{
sum += i;
}
return sum;
});
task.Start();
Console.WriteLine("主线程执⾏其他任务");
Task task1 = task.ContinueWith(t =>
{
Thread.Sleep(1000);
Console.WriteLine($"task = {t.Result}");
});
task1.Wait();//task.Wait();对t.Result不起作⽤,主线程会直接结束
}
}
}
任务的串⾏【没有研究】
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Program
{
static void Main(string[] args)
{
ConcurrentStack<int> stack = new ConcurrentStack<int>();
//t1先串⾏
var t1 = Task.Factory.StartNew(() =>
{
stack.Push(1);
stack.Push(2);
});
//t2,t3并⾏执⾏
var t2 = t1.ContinueWith(t =>
{
int result;
stack.TryPop(out result);
Console.WriteLine("Task t2 result={0},Thread id {1}", result, Thread.CurrentThread.ManagedThreadId);
});
//t2,t3并⾏执⾏
var t3 = t1.ContinueWith(t =>
{
int result;
stack.TryPop(out result);
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();
}
}
⼦任务
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Program
{
static void Main(string[] args)
{
Task<string[]> task = new Task<string[]>(state =>
{
Console.WriteLine("⽗任务开始");
string[] result = new string[2];
new Task(() => { result[0] = "⼦任务1"; }, TaskCreationOptions.AttachedToParent).Start();
new Task(() => { result[1] = "⼦任务2"; }, TaskCreationOptions.AttachedToParent).Start();
Thread.Sleep(1000);
return result;
}, "我是⽗任务,创建了⼦任务,等⼦任务执⾏完才会执⾏结束");
task.ContinueWith(t =>
{
Array.ForEach(t.Result, r => Console.WriteLine(r));
});
task.Start();
task.Wait();
}
}
}
动态并⾏(TaskCreationOptions.AttachedToParent) ⽗任务等待所有⼦任务完成后整个任务才算完成【没有研究过】using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Node
{
public Node Left { get; set; }
public Node Right { get; set; }
public string Text { get; set; }
}
class Program
{
static Node GetNode()
{
Node root = new Node
{
Left = new Node
{
Left = new Node
{
Text = "L-L"
},
Right = new Node
{
Text = "L-R"
},
Text = "L"
},
Right = new Node
{
Left = new Node
{
Text = "R-L"
},
Right = new Node
{
Text = "R-R"
},
Text = "R"
},
Text = "Root"
};
return root;
}
static void Main(string[] args)
{
Node root = GetNode();
DisplayTree(root);
}
static void DisplayTree(Node root)
{
var task = Task.Factory.StartNew(() => DisplayNode(root),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default);
task.Wait();
}
static void DisplayNode(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);
}
}
}
2.3取消任务 CancellationTokenSource【没研究明⽩】
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Program
{
private static int TaskMethod(string name, int seconds, 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 = new CancellationTokenSource();
var longTask = new Task<int>(() => 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 = new CancellationTokenSource();
longTask = new Task<int>(() => 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);
}
}
}
2.4处理任务中的异常
单个任务
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Program
{
static int TaskMethod(string name, int seconds)
{
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<int> 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();
}
}
}
多个任务
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadStudy
{
class Program
{
static int TaskMethod(string name, int seconds)
{
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<int>(() => TaskMethod("Task 3", 3));
var t2 = new Task<int>(() => TaskMethod("Task 4", 2));
var complexTask = Task.WhenAll(t1, t2);
var exceptionHandler = complexTask.ContinueWith(t =>
Console.WriteLine("Result: {0}", t.Result),
TaskContinuationOptions.OnlyOnFaulted
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论