我有一项任务,但其中的进程并不是并行运行的。第二个等待第一个竞争。你能解释一下为什么以及如何纠正这个问题?我希望他们两个同时运行。
第二个问题,我应该使用任务代替线程吗?
提前致谢。
new Task(() =>
{
Counter1();
Counter2();
}).Start();
private void Counter2()
{
for (int i = 0; i < 30; i++)
{
Thread.Sleep(500);
label2.Text = i.ToString();
}
}
private void Counter1()
{
for (int i = 0; i < 30; i++)
{
Thread.Sleep(500);
label3.Text = i.ToString();
if(i == 15)
Thread.Sleep(3000);
}
}
答案 0 :(得分:3)
使用Parallel.Invoke并调用Counter1()
和Counter2()
,如下面的MSDN示例所示(更新()
匿名lambda调用后,调用您的2种方法。
#region ParallelTasks
// Perform three tasks in parallel on the source array
Parallel.Invoke(() =>
{
Console.WriteLine("Begin first task...");
GetLongestWord(words);
}, // close first Action
() =>
{
Console.WriteLine("Begin second task...");
GetMostCommonWords(words);
}, //close second Action
() =>
{
Console.WriteLine("Begin third task...");
GetCountForWord(words, "species");
} //close third Action
); //close parallel.invoke
Console.WriteLine("Returned from Parallel.Invoke");
#endregion
答案 1 :(得分:0)
父任务 - 可以使用子任务
new Task(() =>
{
Task.Factory.StartNew(Counter1);
Task.Factory.StartNew(Counter2);
}).Start();
private void Counter2()
{
for (int i = 0; i < 30; i++)
{
Thread.Sleep(500);
label2.Text = i.ToString();
}
}
private void Counter1()
{
for (int i = 0; i < 30; i++)
{
Thread.Sleep(500);
label3.Text = i.ToString();
if(i == 15)
Thread.Sleep(3000);
}
}e