简体   繁体   English

SQL CLR-lock语句有什么区别吗?

[英]SQL CLR - Does lock statement make any difference?

I have written the following piece of code ( sql clr stored procedure ) that writes messages to a local file. 我已经编写了以下代码(sql clr存储过程),用于将消息写入本地文件。 The problem occurs when multiple connections call the stored proc at the same time. 当多个连接同时调用存储的proc时,会发生此问题。 So I used a lock statement. 所以我用了lock语句。 But this doesn't seem to make any difference? 但这似乎没有什么不同? What am I doing wrong here? 我在这里做错了什么?

lock (SqlContext.Pipe)
{
    StreamWriter sw = File.AppendText("C:\Date.txt");
    int y = 50;

    while (y != 0)
    {
        sw.WriteLine(DateTime.Now + " " + serverName + " -- " + jobId.ToString() );
        System.Threading.Thread.Sleep(new Random().Next());
        y = y - 1;
    }
    sw.Close();

}

lock statement on its own doesn't protect anything. 单独的lock语句不能保护任何内容。 The magic happens only when all threads lock the same object . 只有当所有线程都锁定同一对象时,魔术才会发生。 In you case, each thread locks its own context pipe, the behavior is going to be identical with or without lock. 在您的情况下,每个线程都锁定自己的上下文管道,无论是否锁定,其行为都是相同的。

Besides, from all the damage a CLR procedure can do inside SQL, hijacking a SQL worker to wait in Sleep() is definitely a top offender. 此外,由于CLR过程可能会对SQL内部造成的所有损害,因此劫持SQL工作者以使其在Sleep()中等待绝对是罪魁祸首。 I hope you only use it for experimental purposes. 我希望您仅将其用于实验目的。

To achieve what you probably want, ie. 实现您可能想要的,即。 have only one procedure execute at any time, use an application lock: sp_getapplock . 任何时候只有一个过程可以执行,请使用应用程序锁: sp_getapplock Either wrap the CLR procedure call in T-SQL sp_getapplock / sp_releaseapplock , or execute sp_getapplock on the context connection from your CLR code (and execute sp_releaseapplock on your way out). 可以将CLR过程调用包装在T-SQL sp_getapplock / sp_releaseapplock ,或者在CLR代码的上下文连接上执行sp_getapplock (并在退出时执行sp_releaseapplock)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM