我正在尝试在 HTTP 处理程序中重现线程错误条件。
基本上,ASP.net 工作进程正在创建 2 个线程,它们在加载某个页面时同时调用我的应用程序中的 HTTP 处理程序。
http 处理程序内部是一个非线程安全的资源。因此,当两个线程尝试同时访问它时,就会发生异常。
我可能会在资源周围放置一个锁定语句,但是我想确保事实确实如此。所以我想首先在控制台应用程序中创建情况。
但我无法像 asp.net wp 那样让 2 个线程同时执行一个方法。所以,我的问题是如何创建两个可以同时执行一个方法的线程。
Edit:
底层资源是一个带有用户表(仅具有名称列)的 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);
}
}
}
您可以像这样设置一个静态时间来开始工作。
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)