ASP.NET锁螺纹的方法 [英] ASP.NET lock thread method

查看:184
本文介绍了ASP.NET锁螺纹的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个ASP.NET使用C#web应用形式。我有创造了一个客户新订单的方法。它看起来类似于这样;

I'm developing an ASP.NET forms webapplication using C#. I have a method which creates a new Order for a customer. It looks similar to this;

    private string CreateOrder(string userName) {
        // Fetch current order
        Order order = FetchOrder(userName);
        if (order.OrderId == 0) {
            // Has no order yet, create a new one
            order.OrderNumber = Utility.GenerateOrderNumber();
            order.Save();
        }
        return order;
    }

这里的问题是,它可能是1的客户在两个请求(线程)可能会导致被调用两次这个方法,而另一个线程也是这个方法中。这可以导致创建两个数量级。

The problem here is, it is possible that 1 customer in two requests (threads) could cause this method to be called twice while another thread is also inside this method. This can cause two orders to be created.

如何能够正确地锁定这个方法,因此它只能由一个线程每一个顾客的时间执行?

How can I properly lock this method, so it can only be executed by one thread at a time per customer?

我试过;

    Mutex mutex = null;
    private string CreateOrder(string userName) {
        if (mutex == null) {
            mutex = new Mutex(true, userName);
        }
        mutex.WaitOne();
        // Code from above
        mutex.ReleaseMutex();
        mutex = null;
        return order;
    }

这工作,但在某些情况下它挂在WaitOne的,我不知道为什么。是否有错误,或者我应该用另一种方法来锁定?

This works, but on some occasions it hangs on WaitOne and I don't know why. Is there an error, or should I use another method to lock?

感谢

推荐答案

initiallyOwned 互斥构造函数。如果你创建互斥,最初拥有它,你需要调用 ReleaseMutex 试。

Pass false for initiallyOwned in the mutex ctor. If you create the mutex and initially own it, you need to call ReleaseMutex again.

这篇关于ASP.NET锁螺纹的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆