2014-12-12 2 views
0

TaskFactory 클래스를 사용하여 다중 작업을 병렬로 작성하려고합니다. 처리중인 각 계류중인 transactionId에 대해 하나씩, 최대 5 개의 스레드까지 처리하려고합니다. 각 작업에 취소 토큰을 전달해야합니다. 나는 올바른 길을 가고 있는가? 비동기 VS 동기화를 실행하려면 어떻게해야합니까? 나는 다음과 같습니다Taskfactory 클래스를 사용하여 여러 개의 작업을 병렬로 만드는 방법은 무엇입니까?

public int ProcessPendingTransactions() 
{ 

    //set the max # of threads 
    ThreadPool.SetMaxThreads(5, 5); 

    //create an action 
    //The Run method is what i am trying to create multiple tasks in parallel on 
    Action action = delegate() { abc.Run(transactionId); }; 

    //kick off a new thread async 
    tfact.StartNew(action, MyCTkn, TaskCreationOptions.None, (TaskScheduler)null);  
} 
+0

다음 번에 적절한 언어 태그를 추가하십시오. 나는 C# 태그를 추가했다. – dcastro

+0

감사합니다. 고맙습니다. – generationalVision

+0

세마포어를 사용하는 것이 최대 작업 수를 5 개로 제한하는 더 좋은 방법입니다. –

답변

1

가정하자, 당신은 각각 1 초 (해봐요)를 완료하기 위해 복용 (200 개) 동작을 만들려면 25 개 스레드를 병렬로 실행할. 그런 다음 이론적으로 약 8 초 정도 걸립니다.

async void MainMethod() 
{ 
    var sw = Stopwatch.StartNew(); 

    //Create Actions 
    var actions = Enumerable.Range(0,200) 
          .Select(i=> ((Action)(()=>DoSomething(i)))); 

    //Run all parallel with 25 Tasks-in-parallel 
    await DoAll(actions, 25); 

    Console.WriteLine("Total Time: " + sw.ElapsedMilliseconds); 
} 


void DoSomething(int i) 
{ 
    Thread.Sleep(1000); 
    Console.WriteLine(i + " completed"); 
} 

async Task DoAll(IEnumerable<Action> actions, int maxTasks) 
{ 
    SemaphoreSlim semaphore = new SemaphoreSlim(maxTasks); 

    foreach(var action in actions) 
    { 
     await semaphore.WaitAsync().ConfigureAwait(false); 
     Task.Factory.StartNew(() =>action(), TaskCreationOptions.LongRunning) 
        .ContinueWith((task) => semaphore.Release()); 
    } 

    for (int i = 0; i < maxTasks; i++) 
     await semaphore.WaitAsync().ConfigureAwait(false); 
} 
관련 문제