|
| 1 | +// Copyright © 2010-2017 The CefSharp Authors. All rights reserved. |
| 2 | +// |
| 3 | +// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | + |
| 9 | +namespace CefSharp |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// Wraps <see cref="TaskCompletionSource{T}"/> by providing a way to set its result in an asynchronous |
| 13 | + /// fashion. This prevents the resulting Task continuations from being executed synchronously on the same |
| 14 | + /// thread as the one completing the Task, which may be better when that thread is a CEF UI thread. |
| 15 | + /// </summary> |
| 16 | + /// <typeparam name="T"></typeparam> |
| 17 | + public class AsyncTaskCompletionSource<T> |
| 18 | + { |
| 19 | + private readonly TaskCompletionSource<T> tcs = new TaskCompletionSource<T>(); |
| 20 | + private int resultSet = 0; |
| 21 | + |
| 22 | + /// <summary> |
| 23 | + /// Gets the <see cref="Task{TResult}"/> created by the wrapped <see cref="AsyncTaskCompletionSource{T}"/> instance. |
| 24 | + /// </summary> |
| 25 | + /// <seealso cref="TaskCompletionSource{TResult}.Task"/> |
| 26 | + public Task<T> Task => tcs.Task; |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Sets the wrapped <see cref="TaskCompletionSource{T}"/> instance result in an asynchronous fashion. |
| 30 | + /// This prevents the Task continuations from being executed synchronously on the same thread as the |
| 31 | + /// one calling this method, which is required when this thread is a CEF UI thread. |
| 32 | + /// </summary> |
| 33 | + /// <param name="result">result</param> |
| 34 | + public void TrySetResultAsync(T result) |
| 35 | + { |
| 36 | + if (Interlocked.Exchange(ref resultSet, 1) == 0) |
| 37 | + { |
| 38 | + System.Threading.Tasks.Task.Factory.StartNew(() => tcs.TrySetResult(result), |
| 39 | + CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | +} |
0 commit comments