Пример #1
0
        public virtual Task <T> SubmitAsync <T>(Func <Task <T> > asyncTask, CancellationToken token,
                                                string callerMethodName, Type callerType)
        {
            try
            {
                OnAsyncTaskStarted?.Invoke(this, EventArgs.Empty);
                Task <T> internalTask = Task.Run(asyncTask);
#pragma warning disable VSTHRD103  // Wait synchronously blocks. Use await instead.
                internalTask.Wait();
#pragma warning restore VSTHRD103
                return(internalTask);
            }
            // Unwrap exception wrapped due to using Wait.
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    throw e.InnerException;
                }

                throw;
            }
            finally
            {
                OnAsyncTaskEnded?.Invoke(this, new AsyncTaskEndedEventArgs());
            }
        }
Пример #2
0
        public Task <T> SubmitAsync <T>(Func <Task <T> > asyncTask, CancellationToken token,
                                        string callerMethodName, Type callerType)
        {
            var completionSource = new TaskCompletionSource <T>();

            token.Register(() => completionSource.TrySetCanceled(token));

            _asyncTasksQueue.Enqueue(async() =>
            {
                OnAsyncTaskStarted?.Invoke(this, EventArgs.Empty);
                try
                {
                    if (!token.IsCancellationRequested)
                    {
                        _insideAsync.Value = true;
                        _currentOperationCancellationToken = token;
                        completionSource.TrySetResult(await asyncTask());
                    }
                }
                catch (Exception e)
                {
                    completionSource.TrySetException(e);
                }
                finally
                {
                    var eventArgs = new AsyncTaskEndedEventArgs
                    {
                        CallerName = callerMethodName, CallerType = callerType
                    };
                    OnAsyncTaskEnded?.Invoke(this, eventArgs);
                    _currentOperationCancellationToken = CancellationToken.None;
                    _insideAsync.Value = false;
                }
            });
            return(completionSource.Task);
        }