我有一个话题。在某个时刻,我想做的是检查某个锁是否空闲。如果它是免费的,我希望该线程继续其快乐的方式。如果它不空闲,我想等到它空闲,但实际上并不获取锁。
这是迄今为止我的代码:
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.
}
最佳答案
我认为你有经典的 XY 问题。我想您想要的是与您 SlowMethod
一起启动一个任务,然后使用 UIThreadStartupStuff
继续它是 UI 线程。
Task.Factory.StartNew(()=>SlowMethod())
.ContinueWith(t=>UIThreadStartupStuff(), TaskScheduler.FromCurrentSynchronizationContext());
或使用 async/await (使您的 SlowMethod
返回任务)
try
{
await SlowMethod();
}
catch(...)
{}
UIThreadStartupStuff();
关于c# - 等待锁被释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067781/