c# - 等待锁被释放

标签 c# multithreading locking

我有一个话题。在某个时刻,我想做的是检查某个锁是否空闲。如果它是免费的,我希望该线程继续其快乐的方式。如果它不空闲,我想等到它空闲,但实际上并不获取锁。

这是迄今为止我的代码:

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/

相关文章:

java - Hibernate 无法初始化代理 - 在线程中访问对象时没有 session

c# - ReaderWriterLockSlim 阻塞读取,直到所有排队的写入完成

Java、EJB、所有方法的并发锁

c# - 为什么在另一个枚举声明中允许不同枚举类型之间的操作,而在其他地方不允许?

c# - Visual C# .net 2013 和线程操作指南

c++ - 从 CUDA 设备函数/内核中并行化一个方法

php - Apache 在提供服务之前是否读取锁定文件?

c# - 如何使用矢量 SSE 操作将图像像素数据的字节数组转换为灰度

C# 多个通用列表<t> - 组合它们?

C# 控制台应用程序 : Catching Some Cases of White Spaces