如何解决用Task控制线程
| 在这样的一些代码中for (int i = 0; i < length; i++) //each iteration in another task
{
Method2();
}
//Task.WaitAll()
public void Method2()
{
Method3();
}
public void Method3()
{
Method4();
}
public void Method4()
{
process1.Start(); //this process take a lot of time so next iteration/next task should start in this place
}
我想在其他线程中运行每个迭代,但不是同时运行。一个线程应该转到Method4(),运行它,然后等待结束此过程。稍后另一个具有相同行为等的线程。在Task.WaitAll()中,程序应等待所有线程。
这该怎么做? 1个迭代中有2个任务,ContinueWith或sth?
解决方法
不要打扰
所有迭代都会很快结束执行Method4(),并且您需要该单线程。
在这种约束下,这根本不是任务或线程的方案。
但是,假设Method2()和/或Method3()中发生了实质性的变化,则可以将
for()
循环替换为Parallel.For()
,并在Process代码周围使用简单的lock
:
private static object processLock = new object(); // probably static
public void Method4()
{
lock(processLock)
{
process1.Start();
}
}
但是现在您必须提防TPL创建太多线程。 (在Parallel.For中使用DegreeOfParallelism)。
,如果我理解正确,那么您希望并行运行所有这些进程,但是您想限制同时运行几个进程,对吗?为此,您可以使用限制并发性的信号量(但是请注意,所有线程在整个时间内都将处于挂起状态,因此请将其标记为LongRunning)。
另一件事是,您必须在Method4中等待进程退出。
static SemaphoreSlim semaphore = new SemaphoreSlim (3); // Capacity of 3
List<Task> tasks = new List<Task>();
for (int i = 0; i < length; i++) //each iteration in another task
{
tasks.Add(Task.Factory.StartNew(() =>
{
Method2();
},TaskCreationOptions.LongRunning);
}
Task.WaitAll(tasks)
public void Method2()
{
Method3();
}
public void Method3()
{
Method4();
}
public void Method4()
{
semaphore.Wait();
process1.Start();
process1.WaitForExit();
semaphore.Release();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。