2

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.
}
William Jockusch
  • 26,513
  • 49
  • 182
  • 323

3 Answers3

2

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();
William Jockusch
  • 26,513
  • 49
  • 182
  • 323
Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
2

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();
}
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
-1

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

}

xxa
  • 1,258
  • 9
  • 20