Task 多线程交替运行 求大神指教
白纸黑字 2013-06-05 05:49:48 static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
{
demo dm = new demo
{
ID = i,
Name = "Text" + i,
DownFrom = "中国"
};
que.Enqueue(dm);
}
CancellationTokenSource cts = new CancellationTokenSource();
Task parent = new Task(() =>
{
//创建任务工厂
TaskFactory tf = new TaskFactory(cts.Token, TaskCreationOptions.AttachedToParent, TaskContinuationOptions.AttachedToParent, TaskScheduler.Default);
//添加一组具有相同状态的子任务
Task[] task = new Task[]{
tf.StartNew(() => { test(que, cts.Token); }),
tf.StartNew(() => { test(que, cts.Token); }),
};
});
parent.Start();
parent.Wait();
Console.Read();
}
static demo dm;
static Queue<demo> que = new Queue<demo>();
public static demo test(Queue<demo> list, CancellationToken token)
{
if (token.IsCancellationRequested)
{
}
foreach (var va in list)
{
dm = new demo
{
ID = va.ID,
Name = va.Name,
DownFrom = va.DownFrom
};
Console.WriteLine(dm.ID + "\t" + dm.Name + "\t" + dm.DownFrom + "\t" + Task.CurrentId);
}
return dm;
}
public class demo
{
public int ID { get; set; }
public string Name { get; set; }
public string DownFrom { get; set; }
}
我想要的结果是 两个线程交替运行
0 Text0 中国 1
1 Text1 中国 2
2 Text2 中国 1
3 Text3 中国 2
4 Text4 中国 1
5 Text5 中国 2
6 Text6 中国 1
7 Text7 中国 2
8 Text8 中国 1
9 Text9 中国 2