Reputation: 27295
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.
}
Upvotes: 2
Views: 2235
Reputation: 134005
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();
}
Upvotes: 2
Reputation: 1318
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...
}
Upvotes: -1
Reputation: 33381
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();
Upvotes: 2