使用Lock来停止并发执行不起作用?

Bit*_*ian 0 .net c# concurrency locking azure

我有一个API,我在其中进行大量处理,如发送服务总线队列消息并接收它,向表添加条目,然后最终将事件发送到socket.io服务器.我希望所有这些都受到并发执行的保护.我正在使用Lock,但它似乎没有做到这一点.我错过了什么吗?下面是我的代码

 public class BroadcastController : ApiController
{
private readonly Object _Lock = new Object();

    [HttpPost]
    [ActionName("UploadRecording")]
    public async Task<HttpResponseMessage> UploadRecording()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string path = Path.GetTempPath();            

        var provider = new MultipartFormDataStreamProvider(path);                       

        // Read the form data and return an async task.
        var response = await Request.Content.ReadAsMultipartAsync(provider);

// processing the mime content

lock (_Lock)
            {

                // sending and receiving service bus messages
                // adding records to table
               // sending an event to socket.io

return Request.CreateResponse(HttpStatusCode.OK, new ResponseMessage<PersistedAudioRecord> { SuccessCode = 1, Message = "Broadcast Uploaded", Data = updatedRecord });
}   }    }
Run Code Online (Sandbox Code Playgroud)

Cha*_*ion 5

使_Lock对象保持静态.否则,您为控制器的每个实例使用不同的锁.由于框架创建了一个新的控制器实例来处理每个请求,因此每个请求都锁定在不同的_Lock对象上,因此不会提供并发安全性.

但请注意,即使是静态锁定对象,只有在拥有单个服务器时才能使用.如果您有多个服务器处理请求,则需要通过其他方式管理并发.