










线程生命周期开始于 System.Threading.Thread 类的对象被创建时,结束于线程被终止或完成执行时。
下面列出了线程生命周期中的各种状态:
ThreadPool相比Thread来说具备了很多优势,但是ThreadPool却又存在一些使用上的不方便。比如:
ThreadPool不支持线程的取消、完成、失败通知等交互性操作;ThreadPool不支持线程执行的先后次序;以往,如果开发者要实现上述功能,需要完成很多额外的工作,现在,FCL中提供了一个功能更强大的概念:Task。Task在线程池的基础上进行了优化,并提供了更多的API。在FCL4.0中,如果我们要编写多线程程序,Task显然已经优于传统的方式。以下是一个简单的任务示例:
static void Main(string[] args)
{
Task t = new Task(() =>
{
Console.WriteLine("任务开始工作……");
var t1 = new Task(() => TaskMethod("Task 1"));
t1.Start();
Task.WaitAll(t1);//等待所有任务结束
任务的状态:Start之前为Created,之后为WaitingToRun
Task.Run(() => TaskMethod("Task 2"));
Task.Factory.StartNew(() => TaskMethod("Task 3")); //直接异步的方法
//或者
var t3=Task.Factory.StartNew(() => TaskMethod("Task 3"));
Task.WaitAll(t3);
任务的状态:Start之前为Running,之后为Running
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"));
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
async static void AsyncFunction()
{
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 void Main()
{
Console.WriteLine("主线程执行业务处理.");
AsyncFunction();
Console.WriteLine("主线程执行其他处理");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(string.Format("Main:i={0}", i));
}
Console.ReadLine();
}
}
}
Task<int> task = CreateTask("Task 1");
task.Start();
int result = task.Result;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static Task<int> CreateTask(string name)
{
return new Task<int>(() => TaskMethod(name));
}
static void Main(string[] args)
{
TaskMethod("Main Thread Task");
Task<int> task = CreateTask("Task 1");
task.Start();
int result = task.Result;
Console.WriteLine("Task 1 Result is: {0}", result);
task = CreateTask("Task 2");
task.RunSynchronously();
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
public static void Main()
{
var ret1 = AsyncGetsum();
Console.WriteLine("主线程执行其他处理");
for (int i = 1; i <= 3; i++)
Console.WriteLine("Call Main()");
int result = ret1.Result;
public static void Main()
{
static void Main(string[] args)
{
ConcurrentStack<int> stack = new ConcurrentStack<int>();
public static void Main()
{
Task<string[]> parent = new Task<string[]>(state =>
{
Console.WriteLine(state);
string[] result = new string[2];
TaskCreationOptions.AttachedToParent父任务等待所有子任务完成后整个任务才算完成
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);
}
}
private static int TaskMethod(string name, int seconds, CancellationToken token)
{
Console.WriteLine("Task {0} 正在运行,当前线程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("第一个任务在执行前已被取消");
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("任务已完成,结果为 {0}.", longTask.Result);
}
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.ReadLine();
}
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
);
t1.Start();
t2.Start();
Task.WaitAll(t1, t2);
}
catch (AggregateException ex)
{
ex.Handle(exception =>
{
Console.WriteLine(exception.Message);
return true;
});
}
}
class Program
{
static async Task ThrowNotImplementedExceptionAsync()
{
throw new NotImplementedException();
}
static async Task ThrowInvalidOperationExceptionAsync()
{
throw new InvalidOperationException();
}
static async Task Normal()
{
await Fun();
}
static Task Fun()
{
return Task.Run(() =>
{
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("i={0}", i);
Thread.Sleep(200);
}
});
}
static async Task ObserveOneExceptionAsync()
{
var task1 = ThrowNotImplementedExceptionAsync();
var task2 = ThrowInvalidOperationExceptionAsync();
var task3 = Normal();
try
{
Task allTasks = Task.WhenAll(task1, task2, task3);
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;
IProgress<in T>只提供了一个方法void Report(T value),通过Report方法把一个T类型的值报告给IProgress,然后IProgress<in T>的实现类Progress<in T>的构造函数接收类型为Action<T>的形参,通过这个委托让进度显示在UI界面中。
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()
{
简APM模式(委托)转换为任务,BeginXXX和EndXXX
class Program
{
private delegate string AsynchronousTask(string threadName);
private static string Test(string threadName)
{
Console.WriteLine("开始...");
Console.WriteLine("线程池是线程吗: {0}", Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromSeconds(2));
Thread.CurrentThread.Name = threadName;
return string.Format("线程名称: {0}", Thread.CurrentThread.Name);
}
private static void Callback(IAsyncResult ar)
{
Console.WriteLine("开始一个回调...");
Console.WriteLine("传递给callbak的状态: {0}", ar.AsyncState);
Console.WriteLine("线程池是线程吗: {0}", Thread.CurrentThread.IsThreadPoolThread);
Console.WriteLine("线程池工作线程id: {0}", Thread.CurrentThread.ManagedThreadId);
}
class Program
{
private delegate string AsynchronousTask(string threadName);
private static string Test(string threadName)
{
Console.WriteLine("开始...");
Console.WriteLine("线程池是线程吗: {0}", Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromSeconds(2));
Thread.CurrentThread.Name = threadName;
return string.Format("线程名称: {0}", Thread.CurrentThread.Name);
}
private int MyTest(object i)
{
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 void Call()
{
private async Task<int> MyTest(object i)
{
this.Invoke(new Action(() =>
{
pictureBox1.Visible = true;
}));
HttpClient client = new HttpClient();
var a = await client.GetAsync("http://www.baidu.com");
Task<string> s = a.Content.ReadAsStringAsync();
MessageBox.Show (s.Result);
this.Invoke(new Action(() =>
{
pictureBox1.Visible = false;
}));
return 0;
}
async private void Call()
{
object i = 55;
var t = Task<Task<int>>.Factory.StartNew(new Func<object, Task<int>>(MyTest), i);
}
private async void MyTest()
{
this.Invoke(new Action(() =>
{
pictureBox1.Visible = true;
}));
HttpClient client = new HttpClient();
var a = await client.GetAsync("http://www.baidu.com");
Task<string> s = a.Content.ReadAsStringAsync();
MessageBox.Show (s.Result);
this.Invoke(new Action(() =>
{
pictureBox1.Visible = false;
}));
}
private void Call()
{
var t = Task.Run(new Action(MyTest));
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。