急求帮忙!C#Task怎么在子线程在开子线程,并等待子线程中线程结束
急求帮忙!C#Task如何在子线程在开子线程,并等待子线程中线程结束
如题:
想要在子线程再开线程,并且要最底层的子线程结束以后才进行其他的 操作,因为工作需要。
我写了个例子,如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class TaskTest
{
long num;
public TaskTest(long num)
{
this.num = num;
}
public void Excute()
{
if (this.num > 100000)
{
TaskFactory fac = new TaskFactory();
Task[] pTask = new Task[]{
fac.StartNew(()=>{
long i = 0;
while (i < 50000)
{
i++; System.Threading.Thread.Sleep(1);
if (i % 1000 == 0) { Console.WriteLine("当前i已循环到:" + i); }
}
}),
fac.StartNew(()=>{
long i = 50001;
while (i < this.num)
{
i++; System.Threading.Thread.Sleep(1);
if (i % 1000 == 0) { Console.WriteLine("当前i已循环到:" + i); }
}
})
};
}
}
}
class Program
{
static void Main(string[] args)
{
TaskTest t = new TaskTest(100001);
Task task = new Task(tt =>
{
new Task(() => { t.Excute(); }, TaskCreationOptions.AttachedToParent).Start();
},"父任务");
task.ContinueWith(state => {
Console.WriteLine("执行完成!");
});
task.Start();
Console.ReadKey();
}
}
}
------解决方案--------------------
http://msdn.microsoft.com/zh-cn/library/dd270695(v=vs.100).aspx
如果你的线程所执行的过程中还要阻塞,那么自然这个过程中也要等待它启动的子线程结束。因此你是有两层阻塞代码。
如题:
想要在子线程再开线程,并且要最底层的子线程结束以后才进行其他的 操作,因为工作需要。
我写了个例子,如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class TaskTest
{
long num;
public TaskTest(long num)
{
this.num = num;
}
public void Excute()
{
if (this.num > 100000)
{
TaskFactory fac = new TaskFactory();
Task[] pTask = new Task[]{
fac.StartNew(()=>{
long i = 0;
while (i < 50000)
{
i++; System.Threading.Thread.Sleep(1);
if (i % 1000 == 0) { Console.WriteLine("当前i已循环到:" + i); }
}
}),
fac.StartNew(()=>{
long i = 50001;
while (i < this.num)
{
i++; System.Threading.Thread.Sleep(1);
if (i % 1000 == 0) { Console.WriteLine("当前i已循环到:" + i); }
}
})
};
}
}
}
class Program
{
static void Main(string[] args)
{
TaskTest t = new TaskTest(100001);
Task task = new Task(tt =>
{
new Task(() => { t.Excute(); }, TaskCreationOptions.AttachedToParent).Start();
},"父任务");
task.ContinueWith(state => {
Console.WriteLine("执行完成!");
});
task.Start();
Console.ReadKey();
}
}
}
------解决方案--------------------
http://msdn.microsoft.com/zh-cn/library/dd270695(v=vs.100).aspx
如果你的线程所执行的过程中还要阻塞,那么自然这个过程中也要等待它启动的子线程结束。因此你是有两层阻塞代码。