并发用户使用c#读取和更新mysql
本文关键字:更新 mysql 读取 用户 并发 | 更新日期: 2023-09-27 17:50:53
我的程序有一个问题,通过解决这个问题,它可能可以通过使用单例方法来完成。但是,我从一些文章中读到,他们说,这不是一个很好的方法来实现它,因为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.
因此,当用户创建一条新记录时,获取新运行数的逻辑如下:
- 获取文档类型= "inv",当前年和当前月,
- 如果没有找到。创建一个新的文档类型、年份和月份记录,运行编号为0001。 如果发现
- 。
现在,问题出来了。我的情况是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
我看到的唯一方法是在你调用的方法上使用锁来做数据库管理。
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.
}
}
}
接近预期效果的最简单方法是对document_running字段使用自动递增:https://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html.
警告:请注意,在这种情况下,您的document_running在所有文档中总是唯一的,而不仅仅是对于具有相同类型/年/月的记录。
替代解决方案:使用GUID作为document_running字段。