编程语言
首页 > 编程语言> > c#同时执行2个线程

c#同时执行2个线程

作者:互联网

我试图在HTTP处理程序中重现线程错误条件.

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

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

我可能会在资源周围放置一个锁定语句,但是我想确保它实际上就是这种情况.所以我想首先在控制台应用程序中创建这种情况.

但我不能像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);
            }
        }
    }

解决方法:

你可以设置一个静态时间来开始你的工作.

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
}

标签:c,asp-net,multithreading,httphandler
来源: https://codeday.me/bug/20190531/1188375.html