开发者

How to synchronize threads in ASP.NET

I have ASP.NET application with code like this executing for web request:

ProcessAction(actionId)

I want to be sure that ProcessAction is not executed at the same time for the same actionId, so I need to do somehting like this:

WaitIfActionWithIdIsExecuting(actionId)开发者_JAVA百科 
ProcessAction(actionId)

What .NET synchronization mechanism should I use ? Mutex, Monitor, AutoResetEvent, ManualResetEvent ?

The situation when the thread will need to wait will be very rare.


You can create a string from the id and intern the string, so that you are sure to always have the same string instance for an id, and lock using the string as identifier:

lock (String.Intern(actionId.ToString())) {
  ProcessAction(actionId);
}


You could use locks but in a web context I'd rather do synchronization through the database. Create a table for the actions with a column "status" that signifies the state of the action (InProgress, Pending, Completed, etc.) Of course it depends on your particular task.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜