简体   繁体   中英

Wait for a lock to be released

I have a thread. At a certain point, what I want to do is check if a certain lock is free. If it is free, I want the thread to continue on its merry way. If it is not free, I want to wait until it is free, but then not actually acquire the lock.

Here is my code so far:

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.
}

I think you have classical XY problem. I guess what you want is start a Task with you SlowMethod and then Continue it with the UIThreadStartupStuff is UI thread.

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

or with async/await (make your SlowMethod to return Task)

try
{
   await SlowMethod();
}
catch(...)
{}
UIThreadStartupStuff();

You don't want to use a lock here. You need an event. Either ManualResetEvent or AutoResetEvent .

Remember, locks are used for mutual exclusion. Events are used for signaling.

You have your SlowMethod set the event when it's done. For example:

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();
}

I might not get what you want to achieve, but why not wait on the lock "properly"? After all, it is a clear sign of the lock being free if you can take it. Also, you can release it immediately if it is important.

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...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM