2014-02-24 6 views
0

나는 C# ASP.NET MVC 프로젝트를 가지고 있습니다.
저는 기본적으로 시뮬레이션 옵션을 취소하고 결과를 대조하고 있습니다.
multi-threading을 사용하면 백만 번 이상의 시뮬레이션을 실행할 수 있습니다.
내 코드는 다음과 같다 :스레드 로컬 변수가있는 Parallel.For 루프

public class MyClass 
{ 
    private ConcurrentBag<StuffResult> StuffResults { get; set; } 
    private bool CancellationRequested { get; set; } 

    public void DoAlotOfStuff(int numberOfStuffToDo) 
    { 
     var cancellationTokenSource = new CancellationTokenSource(); 
     var options = new ParallelOptions { CancellationToken = cancellationTokenSource.Token }; 

     Task.Factory.StartNew(() => 
     { 
      if (CancellationRequested) cancellationTokenSource.Cancel(); 
     }); 

     try 
     { 
      Parallel.For(0, numberOfStuffToDo, options, a => 
      { 
       options.CancellationToken.ThrowIfCancellationRequested(); 
       var class1 = new Class1(); 
       var class2 = new Class2(); 
       var class3 = new Class3(); 
       var class4 = new Class4(class1, class2, class3); 
       var result = class4.DoStuff(); 
       StuffResults.Add(result); 
      }); 
     } 
     catch (OperationCanceledException e) 
     { 
      //handle exception 
     } 
    } 
} 

질문 : 각 반복에 대한 새로운 Class1, Class2, Class3Class4 객체의 인스턴스를 피할 수 있습니까? 나는 this msdn 기사를 읽었지만 그것을 이해하지 못한다. 스레드 당 각 객체 당 1 개. 클래스가 그들과 관련된 상태의 일종이있는 경우를 인스턴스화 피할 수 있다면

답변

0

그것은 나에게 충분히 안전 보면 ...

는 모르겠어요. 그렇지 않다면 루프 밖에서 클래스를 선언하거나 DoStuff 메서드를 정적으로 만들 수 있으므로 인스턴스화 된 클래스가 전혀 필요하지 않습니다.

0

나는 이런 식으로 할 것 :

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 

namespace ParallelTest 
{ 
    class Program 
    { 
     static AutoResetEvent autoReset = new AutoResetEvent(false); 

     static void Main(string[] args) 
     { 
      // since this is an async method it will be run in a different thread 
      DoSomething(); 

      // wait for the async method to signal the main thread 
      autoReset.WaitOne(); 

      Console.WriteLine("done"); 

     } 

     async static void DoSomething() 
     { 
      // create some common data 
      const int count = 50000; 
      const int factor = 3; 


      // create some tasks 
      var task1 = Task.Run(() => 
      { 
       int x = 0; 
       for (int i = 0; i < count * 2; ++i) 
       { 
        x += i + factor * 3; 
        Console.WriteLine("task1: " + i + factor * 3); 
       } 
       return x; 
      }); 

      var task2 = Task.Run(() => 
      { 
       int x = 0; 
       for (int i = 0; i < count * 2; ++i) 
       { 
        x += i + factor * 4; 
        Console.WriteLine("task2: " + i + factor * 4); 
       } 
       return x; 
      }); 

      var task3 = Task.Run(() => 
      { 
       int x = 0; 
       for (int i = 0; i < count * 2; ++i) 
       { 
        x += i + factor * 5; 
        Console.WriteLine("task3: " + i + factor * 5); 
       } 
       return x; 
      }); 


      // create a resulttask which will run all the tasks in parallel 
      var resultTask = Task.WhenAll(task1, task2, task3); 

      // start the task and wait till it finishes 
      var results = await resultTask; 

      // display the results 
      for (int i = 0; i < results.Length; ++i) 
      { 
       Console.WriteLine("result" + i + ": " + results[i]); 
      } 

      // signal main thread 
      autoReset.Set(); 
     } 
    } 
}