System.Threading.Tasks.TaskCompletionSource.TrySetResult(TResult)

Here are the examples of the csharp api System.Threading.Tasks.TaskCompletionSource.TrySetResult(TResult) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

48 Examples 7

19 Source : ChildWindowManager.cs
with GNU General Public License v3.0
from atomex-me

private static Task<TResult> OpenDialogAsync<TResult>(ChildWindow dialog, Panel container)
        {
            //void DialogOnMouseUp(object sender, MouseButtonEventArgs args)
            //{
            //    var elementOnTop = container.Children.OfType<UIElement>().OrderBy(c => c.GetValue(Panel.ZIndexProperty)).LastOrDefault();
            //    if (elementOnTop != null && !Equals(elementOnTop, dialog))
            //    {
            //        var zIndex = (int) elementOnTop.GetValue(Panel.ZIndexProperty);
            //        elementOnTop.SetCurrentValue(Panel.ZIndexProperty, zIndex - 1);
            //        dialog.SetCurrentValue(Panel.ZIndexProperty, zIndex);
            //    }
            //}

            //dialog.PreviewMouseDown += DialogOnMouseUp;

            var tcs = new TaskCompletionSource<TResult>();

            void Handler(object sender, RoutedEventArgs args)
            {
                dialog.ClosingFinished -= Handler;
                //dialog.PreviewMouseDown -= DialogOnMouseUp;
                container.Children.Remove(dialog);
                tcs.TrySetResult(dialog.ChildWindowResult is TResult result ? result : default(TResult));
            }

            dialog.ClosingFinished += Handler;

            dialog.IsOpen = true;

            return tcs.Task;
        }

19 Source : DialogWindowBase.cs
with MIT License
from AvaloniaCommunity

private Task<TResult> Procedure(Action action)
        {
            var tcs = new TaskCompletionSource<TResult>();

            void OnceHandler (object sender, EventArgs args)
            {
                tcs.TrySetResult(m_Window.GetResult());
                m_Window.Closed -= OnceHandler;
            }

            m_Window.Closed += OnceHandler;
            Transitionreplacedist.SetDisableTransitions(m_Window as AvaloniaObject, DialogHelper.DisableTransitions);
            action();
            return tcs.Task;
        }

19 Source : TaskEx.cs
with MIT License
from Azure

public static IAsyncResult ToAsyncResult<TResult>(this Task<TResult> task, AsyncCallback callback, object state, bool executeSynchronously = false)
        {
            // Tasks ALWAYS report IAsyncResult.CompletedSynchronously = false.  This can lead to StackOverflow problems
            // when interoping with normal IAsyncResult patterns because if IAsyncResult.CompletedSynchronously == false then
            // it's supposed to be 'safe' to invoke continuations from the AsyncCallback.  This isn't necessarily true
            // with Tasks, so in order to break the stack overflow chain don't preplaced the TaskContinuationOptions.ExecuteSynchronously
            // flag.  However, this comes with a performance hit.  If we have a task that is not completed, it's safe to use 
            // the ExecuteSynchronously flag since we know the task had to complete asynchronously (as opposed to lying to us).
            var continuationOptions = task.IsCompleted || !executeSynchronously ? TaskContinuationOptions.None : TaskContinuationOptions.ExecuteSynchronously;

            if (task.AsyncState == state)
            {
                if (callback != null)
                {
                    task.ContinueWith(
                        t => callback(task),
                        continuationOptions);
                }

                return task;
            }

            var tcs = new TaskCompletionSource<TResult>(state);
            task.ContinueWith(
                (t, s) =>
                {
                    var tcsPtr = (TaskCompletionSource<TResult>)s;
                    if (t.IsFaulted)
                    {
                        tcsPtr.TrySetException(t.Exception.InnerExceptions);
                    }
                    else if (t.IsCanceled)
                    {
                        tcsPtr.TrySetCanceled();
                    }
                    else
                    {
                        tcsPtr.TrySetResult(t.Result);
                    }

                    callback?.Invoke(tcsPtr.Task);
                },
                tcs,
                continuationOptions);

            return tcs.Task;
        }

19 Source : ReceiveBatch.cs
with MIT License
from BreezeHub

protected async Task MakeTransactionAsync()
		{
			
			List<T> data = new List<T>();
			T output = default(T);
			TaskCompletionSource<TResult> completion = null;
			lock(Data)
			{
				completion = _TransactionCreated;
				_TransactionCreated = new TaskCompletionSource<TResult>();
				while(Data.TryDequeue(out output))
				{
					data.Add(output);
				}
			}
			if(data.Count == 0)
				return;
			var dataArray = data.ToArray();
			NBitcoin.Utils.Shuffle(dataArray);


			try
			{
				completion.TrySetResult(await RunAsync(dataArray).ConfigureAwait(false));
			}
			catch(Exception ex)
			{
				completion.TrySetException(ex);
			}
		}

19 Source : BasFunction.cs
with MIT License
from CheshireCaat

[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
        public Task<TResult> GetTask<TResult>()
        {
            var completion = new TaskCompletionSource<TResult>();

            _completion.Task.ContinueWith(task =>
            {
                if (!task.IsFaulted)
                {
                    completion.TrySetResult(((object) task.Result).Convert<TResult>());
                }
                else
                {
                    completion.TrySetException(task.Exception.InnerExceptions);
                }
            });

            return completion.Task;
        }

19 Source : BasRemoteClient.cs
with MIT License
from CheshireCaat

public async Task<TResult> SendAndWaitAsync<TResult>(string type, Params data = null)
        {
            var tcs = new TaskCompletionSource<TResult>();
            SendAsync<TResult>(type, data, result => tcs.TrySetResult(result));
            return await tcs.Task.ConfigureAwait(false);
        }

19 Source : TaskCompletionSourceExtensions.cs
with GNU General Public License v3.0
from Coinigy

public static bool TryCompleteFromCompletedTask<TResult, TSourceResult>(this TaskCompletionSource<TResult> @this, Task<TSourceResult> task) where TSourceResult : TResult
        {
            if (@this == null)
            {
                throw new ArgumentNullException(nameof(@this));
            }

            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            if (task.IsFaulted)
            {
                return @this.TrySetException(task.Exception.InnerExceptions);
            }

            if (task.IsCanceled)
            {
                try
                {
                    task.WaitAndUnwrapException();
                }
                catch (OperationCanceledException exception)
                {
                    var token = exception.CancellationToken;
                    return token.IsCancellationRequested ? @this.TrySetCanceled(token) : @this.TrySetCanceled();
                }
            }
            return @this.TrySetResult(task.Result);
        }

19 Source : TaskCompletionSourceExtensions.cs
with GNU General Public License v3.0
from Coinigy

public static bool TryCompleteFromCompletedTask<TResult>(this TaskCompletionSource<TResult> @this, Task task, Func<TResult> resultFunc)
        {
            if (@this == null)
            {
                throw new ArgumentNullException(nameof(@this));
            }

            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }

            if (resultFunc == null)
            {
                throw new ArgumentNullException(nameof(resultFunc));
            }

            if (task.IsFaulted)
            {
                return @this.TrySetException(task.Exception.InnerExceptions);
            }

            if (task.IsCanceled)
            {
                try
                {
                    task.WaitAndUnwrapException();
                }
                catch (OperationCanceledException exception)
                {
                    var token = exception.CancellationToken;
                    return token.IsCancellationRequested ? @this.TrySetCanceled(token) : @this.TrySetCanceled();
                }
            }
            return @this.TrySetResult(resultFunc());
        }

19 Source : TaskHelpers.cs
with MIT License
from CoreWCF

public static Task<TResult> CancellableAsyncWait<TResult>(this Task<TResult> task, CancellationToken token)
        {
            if (!token.CanBeCanceled)
            {
                return task;
            }

            object[] state = new object[2];
            var tcs = new TaskCompletionSource<TResult>(state);
            state[0] = tcs;
            CancellationTokenRegistration registration = token.Register(OnCancellation<TResult>, state);
            state[1] = registration;
            task.ContinueWith((antecedent, obj) =>
            {
                object[] stateArr = (object[])obj;
                var tcsObj = (TaskCompletionSource<TResult>)stateArr[0];
                var tokenRegistration = (CancellationTokenRegistration)stateArr[1];
                tokenRegistration.Dispose();
                if (antecedent.IsFaulted)
                {
                    tcsObj.TrySetException(antecedent.Exception.InnerException);
                }
                else if (antecedent.IsCanceled)
                {
                    tcsObj.TrySetCanceled();
                }
                else
                {
                    tcsObj.TrySetResult(antecedent.Result);
                }
            }, state, CancellationToken.None, TaskContinuationOptions.HideScheduler, TaskScheduler.Default);

            return tcs.Task;
        }

19 Source : KernelScheduler.cs
with MIT License
from dotnet

private void Run(ScheduledOperation operation)
        {
            _currentTopLevelOperation.Value ??= operation;

            using var logOp = Log.OnEnterAndConfirmOnExit($"Run: {operation.Value}");

            try
            {
                var operationTask = operation
                                    .ExecuteAsync()
                                    .ContinueWith(t =>
                                    {
                                        if (!operation.TaskCompletionSource.Task.IsCompleted)
                                        {
                                            if (t.GetIsCompletedSuccessfully())
                                            {
                                                operation.TaskCompletionSource.TrySetResult(t.Result);
                                            }
                                        }
                                    });

                Task.WaitAny(new[] {
                    operationTask,
                    operation.TaskCompletionSource.Task
                }, _schedulerDisposalSource.Token);

                logOp.Succeed();
            }
            catch (Exception exception)
            {
                if (!operation.TaskCompletionSource.Task.IsCompleted)
                {
                    operation.TaskCompletionSource.SetException(exception);
                }
            }
        }

19 Source : ViewModelBase.cs
with MIT License
from f-miyu

public override void OnNavigatedFrom(INavigationParameters parameters)
        {
            base.OnNavigatedFrom(parameters);

            if (_tcs == null || parameters.GetNavigationMode() == NavigationMode.New)
                return;

            if (parameters.ContainsKey(ParameterKey))
            {
                var parameter = (TResult)parameters[ParameterKey];

                _tcs.TrySetResult(parameter);
            }
            else
            {
                _tcs.TrySetResult(default(TResult));
            }
        }

19 Source : ViewModelBase.cs
with MIT License
from f-miyu

public override void Destroy()
        {
            base.Destroy();

            _tcs?.TrySetResult(default(TResult));
        }

19 Source : DialogExtension.cs
with MIT License
from ghost1372

public static Task<TResult> GetResultAsync<TResult>(this Dialog dialog)
        {
            var tcs = new TaskCompletionSource<TResult>();

            try
            {
                if (dialog.IsClosed)
                {
                    SetResult();
                }
                else
                {
                    dialog.Unloaded += OnUnloaded;
                    dialog.GetViewModel<IDialogResultable<TResult>>().CloseAction = dialog.Close;
                }
            }
            catch (Exception e)
            {
                tcs.TrySetException(e);
            }

            return tcs.Task;

            // ReSharper disable once ImplicitlyCapturedClosure
            void OnUnloaded(object sender, RoutedEventArgs args)
            {
                dialog.Unloaded -= OnUnloaded;
                SetResult();
            }

            void SetResult()
            {
                try
                {
                    tcs.TrySetResult(dialog.GetViewModel<IDialogResultable<TResult>>().Result);
                }
                catch (Exception e)
                {
                    tcs.TrySetException(e);
                }
            }
        }

19 Source : Additionals.cs
with Apache License 2.0
from HMS-Core

public static Task<TResult> CastTask<TResult>(this HuaweiTask HuaweiTask) where TResult : Java.Lang.Object
        {
            var tcs = new TaskCompletionSource<TResult>();

            HuaweiTask.AddOnCompleteListener(new HuaweiTaskCompleteListener(
                t =>
                {
                    if (t.Exception == null)
                        tcs.TrySetResult(t.Result.JavaCast<TResult>());
                    else
                        tcs.TrySetException(t.Exception);
                }));

            return tcs.Task;
        }

19 Source : TaskHelper.cs
with Apache License 2.0
from HMS-Core

public static Task<TResult> CastTask<TResult>(this HuaweiTask huaweiTask)
            where TResult : Java.Lang.Object
        {
            var tcs = new TaskCompletionSource<TResult>();

            huaweiTask.AddOnCompleteListener(new MyCompleteListener(
                t =>
                {
                    if (t.Exception == null)
                        tcs.TrySetResult(t.Result.JavaCast<TResult>());
                    else
                        tcs.TrySetException(t.Exception);
                }));

            return tcs.Task;
        }

19 Source : ContactShieldClass.cs
with Apache License 2.0
from HMS-Core

public static Task<TResult> CastTask<TResult>(this HuaweiTask HuaweiTask)
			where TResult : Java.Lang.Object
		{
			var tcs = new TaskCompletionSource<TResult>();

			HuaweiTask.AddOnCompleteListener(new MyCompleteListener(
				t =>
				{
					if (t.Exception == null)
						tcs.TrySetResult(t.Result.JavaCast<TResult>());
					else
						tcs.TrySetException(t.Exception);
				}));

			return tcs.Task;
		}

19 Source : OpenDeviceHelper.cs
with Apache License 2.0
from HMS-Core

public static Task<TResult> CastTask<TResult>(this HuaweiTask huaweiTask)
			where TResult : Java.Lang.Object
		{
			var tcs = new TaskCompletionSource<TResult>();

			huaweiTask.AddOnCompleteListener(new MyCompleteListener(
				t =>
				{
					if (t.Exception == null)
						tcs.TrySetResult(t.Result.JavaCast<TResult>());
					else
						tcs.TrySetException(t.Exception);
				}));

			return tcs.Task;
		}

19 Source : TaskCompletionSourceExtensions.cs
with MIT License
from i3arnon

public static bool TryCompleteFromCompletedTask<TResult>(
            this TaskCompletionSource<TResult> taskCompletionSource,
            Task<TResult> completedTask)
        {
            if (taskCompletionSource == null) throw new ArgumentNullException(nameof(taskCompletionSource));
            if (completedTask == null) throw new ArgumentNullException(nameof(completedTask));

            switch (completedTask.Status)
            {
                case TaskStatus.Faulted:
                    return taskCompletionSource.TrySetException(completedTask.Exception.InnerExceptions);
                case TaskStatus.Canceled:
                    return taskCompletionSource.TrySetCanceled();
                case TaskStatus.RanToCompletion:
                    return taskCompletionSource.TrySetResult(completedTask.Result);
                default:
                    throw new ArgumentException("Argument must be a completed task", nameof(completedTask));
            }
        }

19 Source : ACompletionUC.Generic.cs
with MIT License
from ipavlu

protected bool SetCompletion(TResult result) => TaskCompletionSource.TrySetResult(result);

19 Source : IqOptionWebSocketClient.cs
with MIT License
from JorgeBeserra

public Task<TResult> SendMessageAsync<TResult>(
            string requestId,
            IWsIqOptionMessageCreator messageCreator,
            IObservable<TResult> observableResult)
        {
            var tcs = new TaskCompletionSource<TResult>();
            var token = new CancellationTokenSource(5000).Token;

            try
            {
                token.ThrowIfCancellationRequested();
                token.Register(() =>
                {
                    if (tcs.TrySetCanceled())
                    {
                        _logger.LogWarning(string.Format(
                            "Wait result for type '{0}', took long times {1} seconds. The result will send back with default {0}\n{2}",
                            typeof(TResult), 5000, messageCreator));
                    }
                });
                
                observableResult
                    .FirstAsync()
                    .Subscribe(x => { tcs.TrySetResult(x); }, token);

                // send message
                SendMessageAsync(requestId, messageCreator).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }
            
            return tcs.Task;
        }

19 Source : AsyncMethodTaskCacheOfTResult.cs
with MIT License
from kaby76

internal static TaskCompletionSource<TResult> CreateCompleted(TResult result)
        {
            var tcs = new TaskCompletionSource<TResult>();
            tcs.TrySetResult(result);
            return tcs;
        }

19 Source : AsyncTaskMethodBuilderOfTResult.cs
with MIT License
from kaby76

public void SetResult(TResult result)
        {
            // Get the currently stored task, which will be non-null if get_Task has already been accessed.
            // If there isn't one, get a task and store it.
            var tcs = m_taskCompletionSource;
            if (tcs == null)
            {
                m_taskCompletionSource = GetTaskForResult(result);
                m_task = m_taskCompletionSource.Task;
            }
            // Slow path: complete the existing task.
            else if (!tcs.TrySetResult(result))
            {
                throw new InvalidOperationException("The Task was already completed.");
            }
        }

19 Source : DefaultResultHandler.cs
with MIT License
from KennanChan

public void SetResult(TResult result)
        {
            TaskCompletionSource.TrySetResult(result);
        }

19 Source : TaskCompletionSourceExtensions.cs
with MIT License
from KennanChan

public static void Wait<TResult>(this TaskCompletionSource<TResult> tcs, Func<TResult> function)
        {
            try
            {
                var result = function();
                tcs.TrySetResult(result);
            }
            catch (Exception e)
            {
                tcs.TrySetException(e);
            }
        }

19 Source : TaskCompletionSourceExtensions.cs
with MIT License
from KennanChan

public static async void Await<TResult>(this TaskCompletionSource<TResult> tcs, Task<TResult> task, Action final = null)
        {
            try
            {
                var result = await task;
                if (task.IsCompleted)
                {
                    tcs.TrySetResult(result);
                }

                if (task.IsCanceled)
                {
                    tcs.TrySetCanceled();
                }

                if (task.IsFaulted)
                {
                    tcs.TrySetException(task.Exception ?? new Exception("Unknown Exception"));
                }
            }
            catch (Exception e)
            {
                tcs.TrySetException(e);
            }
            finally
            {
                final?.Invoke();
            }
        }

19 Source : TaskExtensions.cs
with MIT License
from Kirill-Maurin

static void SelectWithSource<T, TResult>(
            this Task<T> task,
            Func<T, TResult> selector,
            TaskCompletionSource<TResult> tcs)
        {
            if (!task.IsCompleted)
                task.ContinueWith(t =>
                {
                    if (!task.CheckCanceled(tcs) && !task.CheckException(tcs))
                        task.SelectWithSource(selector, tcs);
                });

            try
            {
                tcs.TrySetResult(selector(task.Result));
            }
            catch (Exception e)
            {
                tcs.TrySetException(e);
            }
        }

19 Source : TaskCompletionSourceExtensions.cs
with MIT License
from liuhll

public static async Task<TResult> WaitAsync<TResult>(this TaskCompletionSource<TResult> tcs,
            CancellationToken cancelToken, int timeoutMs = Timeout.Infinite)
        {
            // The overrideTcs is used so we can wait for either the give tcs to complete or the overrideTcs.  We do this using the Task.WhenAny method.
            // one issue with WhenAny is that it won't return when a task is canceled, it only returns when a task completes so we complete the
            // overrideTcs when either the cancelToken is canceled or the timeoutMs is reached.
            //
            var overrideTcs = new TaskCompletionSource<TResult>();
            using (var timeoutCancelTokenSource = (timeoutMs <= 0) ? null : new CancellationTokenSource(timeoutMs))
            {
                var timeoutToken = timeoutCancelTokenSource?.Token ?? CancellationToken.None;
                using (var linkedTokenSource =
                    CancellationTokenSource.CreateLinkedTokenSource(cancelToken, timeoutToken))
                {
                    // This method is called when either the linkedTokenSource is canceled.  This lets us replacedign a value to the overrideTcs so that
                    // We can break out of the await WhenAny below.
                    //
                    void CancelTcs()
                    {
                        if (!tcs.Task.IsCompleted)
                        {
                            // ReSharper disable once AccessToDisposedClosure (in this case, CancelTcs will never be called outside the using)
                            if (timeoutCancelTokenSource?.IsCancellationRequested ?? false)
                                tcs.TrySetException(new TimeoutException($"WaitAsync timed out after {timeoutMs}ms"));
                            else
                                tcs.TrySetCanceled();
                        }

                        overrideTcs.TrySetResult(default(TResult));
                    }

                    using (linkedTokenSource.Token.Register(CancelTcs))
                    {
                        try
                        {
                            await Task.WhenAny(tcs.Task, overrideTcs.Task);
                        }
                        catch
                        {
                            /* ignore */
                        }

                        // We always favor the result from the given tcs task if it has completed.
                        //
                        if (tcs.Task.IsCompleted)
                        {
                            // We do another await here so that if the tcs.Task has faulted or has been canceled we won't wrap those exceptions
                            // in a nested exception.  While technically accessing the tcs.Task.Result will generate the same exception the
                            // exception will be wrapped in a nested exception.  We don't want that nesting so we just await.
                            await tcs.Task;
                            return tcs.Task.Result;
                        }

                        // It wasn't the tcs.Task that got us our of the above WhenAny so go ahead and timeout or cancel the operation.
                        //
                        if (timeoutCancelTokenSource?.IsCancellationRequested ?? false)
                            throw new TimeoutException($"WaitAsync timed out after {timeoutMs}ms");

                        throw new OperationCanceledException();
                    }
                }
            }
        }

19 Source : TaskCompletionSourceExtensions.cs
with MIT License
from liuhll

public static async Task<TResult> WaitAsync<TResult>(this TaskCompletionSource<TResult> tcs,
            int timeoutMs = Timeout.Infinite)
        {
            var overrideTcs = new TaskCompletionSource<TResult>();
            using (var timeoutCancelTokenSource = (timeoutMs <= 0) ? null : new CancellationTokenSource(timeoutMs))
            {
                var timeoutToken = timeoutCancelTokenSource?.Token ?? CancellationToken.None;

                void CancelTcs()
                {
                    if (!tcs.Task.IsCompleted)
                    {
                        // ReSharper disable once AccessToDisposedClosure (in this case, CancelTcs will never be called outside the using)
                        if (timeoutCancelTokenSource?.IsCancellationRequested ?? false)
                            tcs.TrySetException(new TimeoutException($"WaitAsync timed out after {timeoutMs}ms"));
                        else
                            tcs.TrySetCanceled();
                    }

                    overrideTcs.TrySetResult(default(TResult));
                }

                using (timeoutToken.Register(CancelTcs))
                {
                    try
                    {
                        await Task.WhenAny(tcs.Task, overrideTcs.Task);
                    }
                    catch
                    {
                        /* ignore */
                    }

                    if (tcs.Task.IsCompleted)
                    {
                        // We do another await here so that if the tcs.Task has faulted or has been canceled we won't wrap those exceptions
                        // in a nested exception.  While technically accessing the tcs.Task.Result will generate the same exception the
                        // exception will be wrapped in a nested exception.  We don't want that nesting so we just await.
                        await tcs.Task;
                        return tcs.Task.Result;
                    }

                    if (timeoutCancelTokenSource?.IsCancellationRequested ?? false)
                        throw new TimeoutException($"WaitAsync timed out after {timeoutMs}ms");

                    throw new OperationCanceledException();
                }
            }
        }

19 Source : Windows.Foundation.cs
with MIT License
from microsoft

private void Complete(IAsyncInfo asyncInfo, Func<IAsyncInfo, TResult> getResultsFunction, AsyncStatus asyncStatus)
        {
            if (asyncInfo == null)
            {
                throw new ArgumentNullException(nameof(asyncInfo));
            }

            // TODO: AsyncCausality?

            try
            {
                Debug.replacedert(asyncInfo.Status == asyncStatus, "asyncInfo.Status does not match asyncStatus; are we dealing with a faulty IAsyncInfo implementation?");
                if (Task.IsCompleted)
                {
                    Debug.Fail("Expected the task to not yet be completed.");
                    throw new InvalidOperationException("The asynchronous operation could not be completed.");
                }

                // Clean up our registration with the cancellation token, noting that we're now in the process of cleaning up.
                CancellationTokenRegistration ctr;
                lock (this)
                {
                    _completing = true;
                    ctr = _ctr;
                    _ctr = default;
                }
                ctr.Dispose();

                if (asyncStatus != AsyncStatus.Completed && asyncStatus != AsyncStatus.Canceled && asyncStatus != AsyncStatus.Error)
                {
                    Debug.Fail("The async operation should be in a terminal state.");
                    throw new InvalidOperationException("The asynchronous operation could not be completed.");
                }

                TResult result = default(TResult);
                Exception error = null;
                if (asyncStatus == AsyncStatus.Error)
                {
                    error = asyncInfo.ErrorCode;

                    // Defend against a faulty IAsyncInfo implementation
                    if (error is null)
                    {
                        Debug.Fail("IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK).");
                        error = new InvalidOperationException("The asynchronous operation could not be completed.");
                    }
                }
                else if (asyncStatus == AsyncStatus.Completed && getResultsFunction != null)
                {
                    try
                    {
                        result = getResultsFunction(asyncInfo);
                    }
                    catch (Exception resultsEx)
                    {
                        // According to the WinRT team, this can happen in some egde cases, such as marshalling errors in GetResults.
                        error = resultsEx;
                        asyncStatus = AsyncStatus.Error;
                    }
                }

                // Complete the task based on the previously retrieved results:
                bool success = false;
                switch (asyncStatus)
                {
                    case AsyncStatus.Completed:
                        // TODO: AsyncCausality?
                        success = base.TrySetResult(result);
                        break;

                    case AsyncStatus.Error:
                        Debug.replacedert(error != null, "The error should have been retrieved previously.");
                        success = base.TrySetException(error);
                        break;

                    case AsyncStatus.Canceled:
                        success = base.TrySetCanceled(_ct.IsCancellationRequested ? _ct : new CancellationToken(true));
                        break;
                }

                Debug.replacedert(success, "Expected the outcome to be successfully transfered to the task.");
            }
            catch (Exception exc)
            {
                Debug.Fail($"Unexpected exception in Complete: {exc}");

                // TODO: AsyncCausality

                if (!base.TrySetException(exc))
                {
                    Debug.Fail("The task was already completed and thus the exception couldn't be stored.");
                    throw;
                }
            }
        }

19 Source : IqOptionWebSocketClient.cs
with MIT License
from MongkonEiadon

public Task<TResult> SendMessageAsync<TResult>(
            IWsIqOptionMessageCreator messageCreator,
            IObservable<TResult> observableResult)
        {
            var tcs = new TaskCompletionSource<TResult>();
            var token = new CancellationTokenSource(5000).Token;

            try
            {
                token.ThrowIfCancellationRequested();
                token.Register(() =>
                {
                    if (tcs.TrySetCanceled())
                    {
                        _logger.LogWarning(string.Format(
                            "Wait result for type '{0}', took long times {1} seconds. The result will send back with default {0}\n{2}",
                            typeof(TResult), 5000, messageCreator));
                    }
                });
                
                observableResult
                    .FirstAsync()
                    .Subscribe(x => { tcs.TrySetResult(x); }, token);

                // send message
                SendMessageAsync(messageCreator).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                tcs.TrySetException(ex);
            }
            
            return tcs.Task;
        }

19 Source : TaskCompletionSource.cs
with MIT License
from Mutuduxf

public bool SetResult(object result) =>
                _taskSource.TrySetResult((TResult)result);

19 Source : TaskHelper.cs
with MIT License
from NewLifeX

private static Task<TResult> ToTaskContinuation<TResult>(Task task, TResult result)
        {
            var tcs = new TaskCompletionSource<TResult>();
            task.ContinueWith(delegate (Task innerTask)
            {
                if (task.Status == TaskStatus.RanToCompletion)
                {
                    tcs.TrySetResult(result);
                    return;
                }
                tcs.TrySetFromTask(innerTask);
            }, TaskContinuationOptions.ExecuteSynchronously);
            return tcs.Task;
        }

19 Source : TaskHelper.cs
with MIT License
from NewLifeX

private static Boolean TrySetFromTask<TResult>(this TaskCompletionSource<TResult> tcs, Task source)
        {
            if (source.Status == TaskStatus.Canceled) return tcs.TrySetCanceled();

            if (source.Status == TaskStatus.Faulted) return tcs.TrySetException(source.Exception.InnerExceptions);

            if (source.Status == TaskStatus.RanToCompletion)
            {
                var task = source as Task<TResult>;
                return tcs.TrySetResult((task == null) ? default(TResult) : task.Result);
            }
            return false;
        }

19 Source : TaskHelpers.cs
with Apache License 2.0
from OpenRIAServices

[SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "This is a known safe usage of Task.Result, since it only occurs when we know the task's state to be completed.")]
        internal static bool TrySetFromTask<TResult>(this TaskCompletionSource<TResult> tcs, Task source)
        {
            if (source.Status == TaskStatus.Canceled)
            {
                return tcs.TrySetCanceled();
            }

            if (source.Status == TaskStatus.Faulted)
            {
                return tcs.TrySetException(source.Exception.InnerExceptions);
            }

            if (source.Status == TaskStatus.RanToCompletion)
            {
                Task<TResult> taskOfResult = source as Task<TResult>;
                return tcs.TrySetResult(taskOfResult == null ? default(TResult) : taskOfResult.Result);
            }

            return false;
        }

19 Source : TaskHelpersExtensions.cs
with Apache License 2.0
from OpenRIAServices

private static Task CopyResultToCompletionSourceImpl<TTask, TResult>(this TTask task, TaskCompletionSource<TResult> tcs, Func<TTask, TResult> resultThunk)
            where TTask : Task
        {
            // Stay on the same thread if we can
            if (task.IsCompleted)
            {
                switch (task.Status)
                {
                    case TaskStatus.Canceled:
                    case TaskStatus.Faulted:
                        TaskHelpers.TrySetFromTask(tcs, task);
                        break;

                    case TaskStatus.RanToCompletion:
                        tcs.TrySetResult(resultThunk(task));
                        break;
                }

                return TaskHelpers.Completed();
            }

            // Split into a continuation method so that we don't create a closure unnecessarily
            return CopyResultToCompletionSourceImplContinuation(task, tcs, resultThunk);
        }

19 Source : TaskHelpersExtensions.cs
with Apache License 2.0
from OpenRIAServices

[SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")]
        private static Task CopyResultToCompletionSourceImplContinuation<TTask, TResult>(TTask task, TaskCompletionSource<TResult> tcs, Func<TTask, TResult> resultThunk)
            where TTask : Task
        {
            return task.ContinueWith(innerTask =>
            {
                switch (innerTask.Status)
                {
                    case TaskStatus.Canceled:
                    case TaskStatus.Faulted:
                        TaskHelpers.TrySetFromTask(tcs, innerTask);
                        break;

                    case TaskStatus.RanToCompletion:
                        tcs.TrySetResult(resultThunk(task));
                        break;
                }
            }, TaskContinuationOptions.ExecuteSynchronously);
        }

19 Source : TaskHelpersExtensions.cs
with Apache License 2.0
from OpenRIAServices

[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The caught exception type is reflected into a faulted task.")]
        [SuppressMessage("Microsoft.Web.FxCop", "MW1201:DoNotCallProblematicMethodsOnTask", Justification = "The usages here are deemed safe, and provide the implementations that this rule relies upon.")]
        private static Task<TResult> ToTaskContinuation<TResult>(Task task, TResult result)
        {
            TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();

            task.ContinueWith(innerTask =>
            {
                if (task.Status == TaskStatus.RanToCompletion)
                {
                    tcs.TrySetResult(result);
                }
                else
                {
                    tcs.TrySetFromTask(innerTask);
                }
            }, TaskContinuationOptions.ExecuteSynchronously);

            return tcs.Task;
        }

19 Source : Tcs`1.cs
with GNU Lesser General Public License v3.0
from Quahu

public bool Complete(TResult result)
            => _tcs.TrySetResult(result);

19 Source : SignalRPersistentConnectionSyncApiClient.cs
with Apache License 2.0
from Rubius

private Task<TResult> SendAndReceive<TResult>(string command, object data)
        {
            var serializedData = JsonConvert.SerializeObject(data, new JsonSerializerSettings()
            {
                StringEscapeHandling = StringEscapeHandling.EscapeNonAscii,
            });

            var tcs = new TaskCompletionSource<TResult>();

            var callbackId = RegisterCallback(result =>
            {
                if (result is Exception exception)
                {
                    tcs.TrySetException(exception);
                }
                else
                {
                    tcs.TrySetResult((TResult) result);
                }
            });
            if (command == MethodConstants.ServerUploadData)
            {
                _uploadDataCallbackId = callbackId;
            }

            _connection.Send(command + serializedData).

            ContinueWith(task =>
            {
                if (task.IsCanceled)
                {
                    RemoveCallback(callbackId);
                    tcs.TrySetCanceled();
                }
                else if (task.IsFaulted)
                {
                    RemoveCallback(callbackId);
                    tcs.SetException(task.Exception);
                }
            },
            TaskContinuationOptions.NotOnRanToCompletion);

            return tcs.Task;
        }

19 Source : TaskCompletionSource.cs
with MIT License
from Shriek-Projects

public bool SetResult(object result)
            {
                var type = typeof(TResult);
                return this.taskSource.TrySetResult((TResult)result);
            }

19 Source : TaskSetter.cs
with MIT License
from Shriek-Projects

public bool SetResult(TResult value)
        {
            this.tokenSourceLazy.Value.Dispose();
            return this.taskSource.TrySetResult(value);
        }

19 Source : TaskExtensions.cs
with GNU General Public License v3.0
from SteamTools-Team

public static void TrySetResultAsync<TResult>(this TaskCompletionSource<TResult> taskCompletionSource, TResult result)
        {
            Task.Factory.StartNew(delegate
            { taskCompletionSource.TrySetResult(result); }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
        }

19 Source : TaskCompletionSourceExtensions.cs
with MIT License
from stride3d

public static void TrySetResultWithBackgroundContinuations<TResult>([NotNull] this TaskCompletionSource<TResult> @this, TResult result)
        {
            // Set the result on a threadpool thread, so any synchronous continuations will execute in the background.
            Task.Run(() => @this.TrySetResult(result));

            // Wait for the TCS task to complete; note that the continuations may not be complete.
            @this.Task.Wait();
        }

19 Source : TaskCompletionSource_T.cs
with MIT License
from Team-RTCLI

public void SetResult(TResult result)
        {
            if (!TrySetResult(result))
            {
                ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted);
            }
        }

19 Source : TaskExtensions.cs
with Mozilla Public License 2.0
from vlingo-net

public static Task<TResult> ToApm<TResult>(this Task<TResult> task, AsyncCallback? callback, object state)
        {
            if (task.AsyncState == state)
            {
                if (callback != null)
                {
                    task.ContinueWith(delegate { callback(task); },
                        CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
                }

                return task;
            }

            var tcs = new TaskCompletionSource<TResult>(state);
            task.ContinueWith(delegate
            {
                if (task.IsFaulted)
                {
                    if (task.Exception != null)
                    {
                        tcs.TrySetException(task.Exception.InnerExceptions);
                    }
                }
                else if (task.IsCanceled)
                {
                    tcs.TrySetCanceled();
                }
                else
                {
                    tcs.TrySetResult(task.Result);
                }

                if (callback != null)
                {
                    callback(tcs.Task);
                }
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
            return tcs.Task;
        }

19 Source : TaskCompletionSourceExtensions.cs
with MIT License
from xuanye

public static bool TrySetFromTask<TResult>(this TaskCompletionSource<TResult> resultSetter, Task task)
        {
            switch (task.Status)
            {
                case TaskStatus.RanToCompletion: return resultSetter.TrySetResult(task is Task<TResult> ? ((Task<TResult>)task).Result : default(TResult));
                case TaskStatus.Faulted: return resultSetter.TrySetException(task.Exception.InnerExceptions);
                case TaskStatus.Canceled: return resultSetter.TrySetCanceled();
                default: throw new InvalidOperationException("The task was not completed.");
            }
        }

19 Source : Utilities.cs
with MIT License
from ymassad

public static bool TryCompleteFromCompletedTask<TResult>(
            this TaskCompletionSource<TResult> taskCompletionSource,
            Task<TResult> completedTask)
        {
            if (completedTask.Status == TaskStatus.Faulted)
                return taskCompletionSource.TrySetException(completedTask.Exception.InnerExceptions);
            if (completedTask.Status == TaskStatus.Canceled)
                return taskCompletionSource.TrySetCanceled();
            if (completedTask.Status == TaskStatus.RanToCompletion)
                return taskCompletionSource.TrySetResult(completedTask.Result);

            throw new Exception("Task is not completed");
        }

19 Source : TunInterface.cs
with GNU General Public License v3.0
from YtFlow

internal ValueTask<TResult> executeLwipTask<TResult> (Func<TResult> act)
        {
            TaskCompletionSource<TResult> tcs = new TaskCompletionSource<TResult>();
            taskChannel.Writer.TryWrite(() =>
            {
                try
                {
                    var res = act();
                    tcs.TrySetResult(res);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            });
            return new ValueTask<TResult>(tcs.Task);
        }