Skip to content

Threading Examples

Chris Dahlberg edited this page Mar 18, 2019 · 2 revisions

AsyncLazy<T>

AsyncLazy<T> is an async-friendly variant of Lazy<T>:

Task<string> GetValueAsync() { return Task.FromResult("Example"); }

AsyncLazy<string> lazyValue = AsyncLazy.Create(() => GetValueAsync());

// AsyncLazy<T> can be awaited directly
string value = await lazyValue;

// The .Value property can also be awaited, which allows the .ConfigureAwait method to be called.
string value2 = await lazyValue.Value.ConfigureAwait(false);

AsyncLock

AsyncLock is an async-friendly variant of the lock statement:

var asyncLock = new AsyncLock();

using (await asyncLock.AcquireAsync().ConfigureAwait(false))
{
    // Add code here that will only run when the lock is acquired
}

AsyncAutoResetEvent

AsyncAutoResetEvent is an async-friendly variant of the AutoResetEvent class:

var resetEvent = new AsyncAutoResetEvent(false);

// To wait for resetEvent to be set:
await resetEvent.WaitOneAsync().ConfigureAwait(false);

// In another thread, set the event and allow waiting threads to proceed:
await resetEvent.SetAsync().ConfigureAwait(false);

AsyncManualResetEvent

AsyncManualResetEvent is an async-friendly variant of the ManualResetEvent class:

var resetEvent = new AsyncManualResetEvent(false);

// To wait for resetEvent to be set:
await resetEvent.WaitOneAsync().ConfigureAwait(false);

// In another thread, set (to allow waiting threads to proceed) or reset (to block other threads) the event:
resetEvent.Set();
resetEvent.Reset();

TaskExtensions

The TaskExtensions class provides extension methods for the Task class:

Task task = Task.CompletedTask;

// WithTimeout extension methods that accept the timeout specified in milliseconds
Task taskWithTimeout = task.WithTimeout(3000);

// WithTimeout extension methods that accept the timeout specified as a TimeSpan
Task taskWithTimeout2 = task.WithTimeout(TimeSpan.FromSeconds(3));

// A Wait extension method that accepts a timeout specified as a TimeSpan and a cancellation token
var cancellationToken = new CancellationToken();
task.Wait(TimeSpan.FromSeconds(3), cancellationToken);
Clone this wiki locally