我有一个多客户端应用程序,需要从两个数据库表中检索和更新数据:
每个客户端都需要从top
检索下一个(SerialNumber table
)未使用的序列号,将其标记为已使用,并使用{{更新NextSerial
表中的WorkOrder
1}}价值
如何确保每个检索操作(选择和2个更新)将单独进行?我可以在多个查询中使用某种锁吗?
答案 0 :(得分:0)
这是我提出的解决方案:
一个WCF service
来处理客户端逐个调用as described here:
//set the service to receive one call at a time
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class Service1 : IService1
{
StringBuilder sb = new StringBuilder();
private SqlConnection con = new SqlConnection(
@"Data Source=YOAV-DEV\SQLEXPRESS2012;
Initial Catalog=Test;Integrated Security=True");
private string query = @"DECLARE @val int;
SET @val =(select top(1) VALUE from SerialNumber where Used = 0);
UPDATE SerialNumber SET Used = 1 WHERE Value = @val;
UPDATE WorkOrder SET NextSerial = (@val +1);
SELECT @val;";
public string GetData()
{
//dapper dot net query
var res = con.Query<int>(query).Single();
return res.ToString();
}
}
用于测试它的WPF
应用程序:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 50; i++)
{
Thread t = new Thread(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(Helpers.GetRandomInt(1, 5)));
var value = sr.GetData();
Application.Current.Dispatcher.Invoke(
new Action(() => { txt1.Text += value + Environment.NewLine; }));
});
t.Start();
}
}
从Console Application
开始执行多次:
static void Main(string[] args)
{
string path = @"C:\Visual Studio 2013\Projects\WcfTester\WcfTester\bin\Debug\WcfTester.exe";
for (int i = 0; i < 5; i++)
{
Process.Start(path);
}
}
我想使用WCF service
可能对此有些过分,但缺乏如何在SQL Server
级别处理此问题的知识,此解决方案适用于我。