开发者

Control threads with Task

In some code like this

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/nex开发者_如何学JAVAt task should start in this place
}

I'd like run each iteration in other thread, but not all at one. One thread should go to Method4(), run it, and wait to ending this process. Later another thread with the same behavior etc. And in Task.WaitAll() program should wait for all threads.

How to do this? 2 Tasks in one iteration, ContinueWith or sth?


Don't bother.

All iterations quickly end up executing Method4() and you want that single threaded.

Under that constraint this is not a scenario for Tasks or Threads at all.


But assuming there is something substantial happening in Method2() and/or Method3(), you could replace the for() loop with Parallel.For() and use a simple lock around the Process code:

private static object processLock = new object();  // probably static

public void Method4()
{
   lock(processLock)
   {
       process1.Start(); 
   }
}

But now you have to guard against the TPL creating too many Threads. (use DegreeOfParallelism in Parallel.For).


if I understand correctly you want to run all these processes in paraller, but you want to limit how many processes will run concurrently right? For that you can use semaphores, which limit concurrency (but be aware that all threads will be all pending whole time - so mark them as LongRunning).

another thing is that you must wait in Method4 for process to exit.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜