并发用户使用c#读取和更新mysql

时间:2015-05-26 15:00:24

标签: c# mysql singleton record-locking

我的程序有问题,通过解决这个问题,可以通过使用单例方法来完成。但是,我从一些文章中读到,他们说,这不是实现它的好方法,因为asp.net应用程序并发用户可能会有很多。

我的问题是,系统运行编号基于数据库示例中的特定记录:

  • DOCUMENT_TYPE =" INV" ,document_year = 2015,document_month = 04,document_running = 0102。
  • DOCUMENT_TYPE =" INV" ,document_year = 2015,document_month = 05,document_running = 0002。

因此,当用户创建新记录时,获取新运行编号的逻辑如下:

  1. 获取文档类型=" inv" ,当年和当月,
  2. 如果没有找到。使用运行编号0001创建新的文档类型,年份和月份记录。
  3. 如果找到。跑+ 1。
  4. 现在,问题就出来了。我的情况是5位用户收到了记录信息 当他们按下"保存"按钮创建新记录: - document_type =" INV" ,document_year = 2015,document_month = 05,document_running = 0002。

    和5个用户获得相同的运行号INV15-05-0003(在0002 + 1之后)。 右边应该是INV15-05-0003,INV15-05-0004,INV15-05-0005,INV15-05-0006和INV15-05-0007。

    如果所有用户都收到错误/过时的信息,我们应该怎么做。 希望你们都能理解我糟糕的英语。 问候, MH

2 个答案:

答案 0 :(得分:0)

您可以接近所需效果的最简单方法是对document_running字段使用自动递增:https://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

警告:请注意,在这种情况下,您的document_running在所有文档中始终是唯一的,而不仅仅是对于具有相同类型/年/月的记录。

替代解决方案: 使用GUID作为document_running字段。同样的警告适用。

答案 1 :(得分:0)

我看到的唯一方法是对要调用的方法使用锁来进行数据库管理。

public class Dal
{
    private static object syncObject = new object();

    public static void InsertUpdate(...) 
    {
        lock (syncObject)
        {
            // 1. Get the document type = "inv" , current year and current month,
            // 2. If not found. create a new document type , year and month record with the running number 0001.
            // 3. if found. running + 1.
        }
    }
}
相关问题