C# 是一种广泛使用的面向对象编程语言,具有许多优秀的特性,例如面向对象编程、类型安全和强类型检查等。在 C# 中,可以使用并行和串行方式来处理任务,以提高程序的性能和效率。本文将介绍如何使用 C# 编写一个例子来实现任务的串行和并行。
一个例子
等待任务的方法包括等待它们执行完成,可以通过调用它们的 Wait
方法,或者查看它们的 Result
属性。另外,我们也可以调用 Task.WaitAll
等待所有任务执行完成,或者调用 Task.WaitAny
等待任意一个任务执行完成。
C#private void btnRun_Click(object sender, EventArgs e)
{
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);
this.BeginInvoke(new Action(() =>
{
txtValue.AppendText("Task t2 result=" + result + ",Thread id " + Thread.CurrentThread.ManagedThreadId+System.Environment.NewLine);
}));
});
//t2,t3并行执行
var t3 = t1.ContinueWith(t =>
{
int result;
stack.TryPop(out result);
this.BeginInvoke(new Action(() =>
{
txtValue.AppendText("Task t3 result=" + result + ",Thread id " + Thread.CurrentThread.ManagedThreadId + System.Environment.NewLine);
}));
});
Task.WaitAll(t2, t3);
//t4串行执行
var t4 = Task.Factory.StartNew(() =>
{
stack.Push(3);
this.BeginInvoke(new Action(() =>
{
txtValue.AppendText("Task t4 push,Thread id " + Thread.CurrentThread.ManagedThreadId + System.Environment.NewLine);
}));
});
t4.Wait();
}
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!