用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();
}
    

要回复问题请先登录注册