2011-02-27 108 views
3

我想重现HTTP处理程序中的线程错误条件。c#同时执行2个线程

基本上,ASP.net工作人员程序正在创建2个线程,在加载某个页面时同时在我的应用程序中调用HTTP处理程序。

在http处理程序中,是一个不是线程安全的资源。因此,当2个线程同时尝试访问它时会发生异常。

我可能会在资源周围放置一个锁定语句,但是我想确保事实如此。所以我想先在控制台应用程序中创建情况。

但我不能得到2线程执行一个方法在同一时间像asp.net wp。所以,我的问题是如何创建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

如果没有看到您的代码,很难判断出现了什么问题。请告诉我们你已经尝试了什么。 – 2011-02-27 14:21:17

回答

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

谢谢史蒂夫,我试过这段代码,但它不能重现异常,有没有其他方法可以调试它? – Raghu 2011-02-27 14:35:47

+0

我会产生更多的线程,直到它发生,如果它没有发生,那么你的问题可能在别处。另外,请参阅我的编辑,直到全部启动它们之后,才会加入生成的线程。抱歉。 – 2011-02-27 17:07:16