public Task<IDisposable> TryEnterAsync(
TimeSpan timeout
)
Public Function TryEnterAsync (
timeout As TimeSpan
) As Task(Of IDisposable)
public:
Task<IDisposable^>^ TryEnterAsync(
TimeSpan timeout
)
function TryEnterAsync(timeout);
The following illustrates an example of using try-catch to detect a failure to take the lock.
AsyncLock asyncLock = new AsyncLock();
try
{
using IDisposable token = await asyncLock.TryEnterAsync();
// Critical region
}
catch (TaskCanceledException)
{
// Lock failed
}
The following illustrates an example of using ContinueWithTResult(FuncTask, TResult) to detect a failure to take the lock.
AsyncLock asyncLock = new AsyncLock();
await asyncLock.TryEnterAsync().ContinueWith(async tokenTask =>
{
if (tokenTask.IsCanceled)
{
// Lock failed
return;
}
using IDisposable token = await tokenTask;
// Critical region
}).Unwrap();
TaskCanceledException | The timeout expires before the lock could be taken. |