共享资源锁 [英] Shared Resource Lock
问题描述
我在.NET 4.5-Web API自助主机上使用C#.服务器端我有一个进程不是线程安全的:它一次只能处理一个请求.如何在控制器代码中锁定此资源(进程),以便按顺序为客户端提供服务,等待资源释放后再使用它?像这样:
I'm using C# on .NET 4.5 - Web API Self Host. Server-side I've a process that is not thread safe: it can serve one request at a time. How can I lock this resource (process) in the controller code, so that clients are served sequentially, waiting for the resource to be freed before using it? Something like:
while(true){
if(!process.isLocked)
break;
}
lock(process)
do(work)
unlock(process)
warn(others)
任何代码段或建议都值得赞赏.预先感谢.
Any code snippet or suggestion are appreciated. Thanks in advance.
推荐答案
如果您要查找要执行的每个线程,但一次只能执行一个,则可以将 lock
语句与静态对象:
If you're looking for each thread to execute, but only one at a time, then you can use the lock
statement with a static object:
private static object lockobj = new object();
public void DoWorkWhenNotBusy()
{
lock (lockobj)
{
// do work
Console.WriteLine("Working #1 (should always complete)...");
Thread.Sleep(500);
}
}
如果您希望线程在对象被锁定时立即返回,则可以这样编写它(双重检查锁定):
If you want the thread to return immediately if the object is locked, then you can write it like this (double-checked locking):
private static object lockobj2 = new object();
private volatile bool locked = false;
public void DoWorkIfNotBusy()
{
if (!locked)
{
lock (lockobj2)
{
if (!locked)
{
locked = true;
// do work
Thread.Sleep(500);
Console.WriteLine("Working #2 (only if not busy)...");
}
locked = false;
}
}
}
测试示例:
for (int i = 0; i < 10; i++)
{
var ts = new ThreadStart(DoWorkWhenNotBusy);
Thread t = new Thread(ts);
t.Start();
var ts2 = new ThreadStart(DoWorkIfNotBusy);
Thread t2 = new Thread(ts2);
t2.Start();
Console.WriteLine("{0} started", i);
}
这篇关于共享资源锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!