2011-02-27 7 views
3

HTTP 처리기 내에서 스레드 오류 조건을 재현하려고합니다.C# 동시에 두 개의 스레드를 실행하십시오.

기본적으로 ASP.net 작업자 procecss는 특정 페이지가로드 될 때 기본적으로 응용 프로그램에서 HTTP 처리기를 호출하는 2 개의 스레드를 만듭니다.

http 처리기의 내부는 스레드로부터 안전하지 않은 리소스입니다. 따라서 2 개의 스레드가 동시에 액세스하려고하면 예외가 발생합니다.

잠재적으로 리소스 주위에 lock 문을 넣을 수는 있지만 실제로 사실인지 확인하고 싶습니다. 그래서 먼저 콘솔 응용 프로그램에서 상황을 만들고 싶었습니다.

하지만 나는 asp.net wp와 같은 방법으로 동시에 2 개의 스레드를 실행할 수 없다. 그래서, 내 질문은 어떻게 동시에 메서드를 실행할 수있는 2 스레드를 만들 수 있습니다.

편집 :

기본이되는 자원이 사용자 테이블과 SQL 데이터베이스 (이름 만 열이)입니다. 여기에 내가 시도한 샘플 코드가있다.

[TestClass] 
    public class UnitTest1 
    { 
     [TestMethod] 
     public void Linq2SqlThreadSafetyTest() 
     { 
      var threadOne = new Thread(new ParameterizedThreadStart(InsertData)); 
      var threadTwo = new Thread(new ParameterizedThreadStart(InsertData)); 

      threadOne.Start(1); // Was trying to sync them via this parameter. 
      threadTwo.Start(0); 

      threadOne.Join(); 
      threadTwo.Join(); 
     } 


     private static void InsertData(object milliseconds) 
     { 
      // Linq 2 sql data context 
      var database = new DataClassesDataContext(); 

      // Database entity 
      var newUser = new User {Name = "Test"}; 

      database.Users.InsertOnSubmit(newUser); 

      Thread.Sleep((int) milliseconds); 

      try 
      { 
       database.SubmitChanges(); // This statement throws exception in the HTTP Handler. 
      } 

      catch (Exception exception) 
      { 
       Debug.WriteLine(exception.Message); 
      } 
     } 
    } 
+0

코드를 보지 않으면 무엇이 잘못되었는지 알기가 어렵습니다. 이미 시도한 것을 보여주세요. –

답변

5

이와 같이 작업을 시작할 정적 시간을 설정할 수 있습니다.

private static DateTime startTime = DateTime.Now.AddSeconds(5); //arbitrary start time 

static void Main(string[] args) 
{ 
    ThreadStart threadStart1 = new ThreadStart(DoSomething); 
    ThreadStart threadStart2 = new ThreadStart(DoSomething); 
    Thread th1 = new Thread(threadStart1); 
    Thread th2 = new Thread(threadStart2); 

    th1.Start();    
    th2.Start(); 

    th1.Join(); 
    th2.Join(); 

    Console.ReadLine(); 
} 

private static void DoSomething() 
{ 
    while (DateTime.Now < startTime) 
    { 
     //do nothing 
    } 

    //both threads will execute code here concurrently 
} 
+0

감사합니다 스티브,이 코드를 시도했지만 예외를 재현 couldnt, 그것을 디버깅 할 수있는 다른 방법이 있습니까? – Raghu

+0

일어날 때까지 나는 더 많은 스레드를 생성 할 것이고, 그렇지 않다면 문제는 다른 곳에있을 것입니다. 또한, 내 편집을보고, 당신이 그들을 시작하기 전까지는 스폰 된 스레드에 참여하지 않으려합니다. 죄송합니다. –

관련 문제