我有一个帖子。在某个时刻,我想做的是检查某个锁是否是免费的。如果它是免费的,我希望线程继续它的快乐方式。如果它不是免费的,我想等到它是免费的,但实际上并没有获得锁定。
到目前为止,这是我的代码:
private object LockObject = new Object();
async void SlowMethod() {
lock (LockObject) {
// lotsa stuff
}
}
void AppStartup() {
this.SlowMethod();
UIThreadStartupStuff();
// now, I want to wait on the lock. I don't know where/how the results
// of SlowMethod might be needed. But I do know that they will be needed.
// And I don't want to check the lock every time.
}
答案 0 :(得分:2)
我认为你有经典的XY问题。我想你想要的是与SlowMethod
一起开始一个任务,然后用UIThreadStartupStuff
继续它是UI线程。
Task.Factory.StartNew(()=>SlowMethod())
.ContinueWith(t=>UIThreadStartupStuff(), TaskScheduler.FromCurrentSynchronizationContext());
或使用async / await(让你的SlowMethod
返回任务)
try
{
await SlowMethod();
}
catch(...)
{}
UIThreadStartupStuff();
答案 1 :(得分:2)
你不想在这里使用锁。你需要一个活动。 ManualResetEvent或AutoResetEvent。
请记住,锁用于互斥。事件用于信令。
您的SlowMethod
设置了事件。{p>例如:
private ManualResetEvent DoneEvent = new ManualResetEvent(false);
async void SlowMethod() {
// lotsa stuff
// done with lotsa stuff. Signal the event.
DoneEvent.Set();
}
void AppStartup() {
this.SlowMethod();
UIThreadStartupStuff();
// Wait for the SlowMethod to set the event:
DoneEvent.WaitOne();
}
答案 2 :(得分:-1)
我可能得不到你想要达到的目标,但为什么不“正确”等待锁? 毕竟,如果你能拿到它,这是一个明显的锁定自由的迹象。 此外,如果重要,您可以立即将其释放。
void AppStartup() {
this.SlowMethod();
UIThreadStartupStuff();
// now, I want to wait on the lock. I don't know where/how the results
// of SlowMethod might be needed. But I do know that they will be needed.
// And I don't want to check the lock every time.
lock (LockObject) {
// nothing, you now know the lock was free
}
// continue...
}