Gemstone Threading Library
Show/Hide TOC

# AsyncLockTryEnterAsync(TimeSpan) Method

Attempts to obtain exclusive access to the lock.

## Definition

Namespace: Gemstone.Threading
Assembly: Gemstone.Threading (in Gemstone.Threading.dll) Version: 1.0.173 -- Release Build+b43e687700b23322cdf6cd7642c9e1eac79619dd
C#
View Source Request Example

    public Task<IDisposable> TryEnterAsync(
    	TimeSpan timeout
    )

VB
View Source Request Example

    Public Function TryEnterAsync (
    	timeout As TimeSpan
    ) As Task(Of IDisposable)

C++
View Source Request Example

    public:
    Task<IDisposable^>^ TryEnterAsync(
    	TimeSpan timeout
    )

JavaScript
View Source Request Example

    function TryEnterAsync(timeout);

#### Parameters

timeout TimeSpan
  The amount of time to wait before failing to take the lock.

#### Return Value

Task IDisposable
A task that, if cancelled, indicates the lock was not taken, and must be awaited to obtain the token that will release the lock on Dispose.

## Remarks

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

## Exceptions

TaskCanceledException | The timeout expires before the lock could be taken.

## See Also

#### Reference

AsyncLock Class
TryEnterAsync Overload
Gemstone.Threading Namespace