gpt4 book ai didi

c# - 等待锁被释放

转载 作者:行者123 更新时间:2023-12-03 13:19:52 26 4
gpt4 key购买 nike

我有一个线程。在某个时候,我想做的就是检查某个锁是否可用。如果它是免费的,我希望线程继续其愉快的方式。如果它不是免费的,我想等到它免费后才真正获得锁。

到目前为止,这是我的代码:

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启动一个Task,然后用uit_code is UI thread继续执行。

Task.Factory.StartNew(()=>SlowMethod())
.ContinueWith(t=>UIThreadStartupStuff(), TaskScheduler.FromCurrentSynchronizationContext());

或使用async/await(使您的 UIThreadStartupStuff返回Task)
try
{
await SlowMethod();
}
catch(...)
{}
UIThreadStartupStuff();

关于c# - 等待锁被释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26067781/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com