public async Task Enqueue_Action_Should_Cancel_Not_Started_Task_When_OnDispose() { Task newTask = null, notstarted = null; bool Done = false; //arrange using (var target = new MonoThreadedQueue(t => t.Priority = ThreadPriority.Highest)) { newTask = target.Enqueue(() => TaskFactory(3)); while (_RunningThread == null) { Thread.Sleep(100); } notstarted = target.Enqueue(() => { Done = true; }); } await newTask; TaskCanceledException error = null; try { await notstarted; } catch (TaskCanceledException e) { error = e; } notstarted.IsCanceled.Should().BeTrue(); error.Should().NotBeNull(); Done.Should().BeFalse(); }
public async Task Enqueue_Action_Should_Cancel_Task_When_On_Disposed_Queue() { MonoThreadedQueue queue = null; //arrange using (queue = new MonoThreadedQueue()) { var task = queue.Enqueue(() => TaskFactory()); } bool Done = false; Task newesttask = queue.Enqueue(() => { Done = true; }); TaskCanceledException error = null; try { await newesttask; } catch (TaskCanceledException e) { error = e; } newesttask.IsCanceled.Should().BeTrue(); error.Should().NotBeNull(); Done.Should().BeFalse(); }
public void Throws_DelegateThrowsDerivedException_ReturnsException() { var expectedException = new TaskCanceledException(); var result = AsyncAssert.Throws <OperationCanceledException>(() => { throw expectedException; }); Assert.Same(expectedException, result); }
public async Task CancelsAsync_DelegateCancelsWithDerivedException_ReturnsException() { var expectedException = new TaskCanceledException(); var result = await AsyncAssert.CancelsAsync(async() => { await Task.Yield(); throw expectedException; }); Assert.Same(expectedException, result); }
public void FaultedTaskCanceledException_SimplePropertiesAreAttached() { // Arrange var innerException = new Exception("Inner exception message"); var task = Task.FromException(innerException); var ex = new TaskCanceledException(task); // Act var exceptionDetails = ExtractExceptionDetails(LogAndDestructureException(ex)); // Assert Assert_ContainsPropertyWithValue(exceptionDetails, "CancellationToken", "CancellationRequested: false"); var taskProperty = ExtractProperty(exceptionDetails, nameof(TaskCanceledException.Task)); var taskPropertyObject = taskProperty.Value.Should().BeOfType <JObject>().Which; Assert_ContainsPropertyWithValue(taskPropertyObject, nameof(Task.Status), nameof(TaskStatus.Faulted)); Assert_ContainsPropertyWithValue(taskPropertyObject, nameof(Task.CreationOptions), nameof(TaskCreationOptions.None)); var taskException = ExtractProperty(taskPropertyObject, nameof(Task.Exception)); var taskExceptionObject = taskException.Should().BeOfType <JProperty>() .Which.Value.Should().BeOfType <JObject>() .Which; var typeOfTaskException = ExtractProperty(taskExceptionObject, "Type"); typeOfTaskException.Should().BeOfType <JProperty>() .Which.Value.Should().BeOfType <JValue>() .Which.Value.Should().BeOfType <string>() .Which.Should().Be("System.AggregateException"); }
/// <summary> /// Determines if the stream with given path on the server is a directory or a terminating file. /// This is used exclusively for download. /// </summary> /// <param name="streamPath">The relative path to the stream.</param> /// <returns> /// True if the stream is a directory, false otherwise. /// </returns> /// <exception cref="System.Threading.Tasks.TaskCanceledException"></exception> public bool IsDirectory(string streamPath) { var stopWatch = new Stopwatch(); stopWatch.Start(); var task = _client.FileSystem.GetFileStatusAsync(_accountName, streamPath, cancellationToken: _token); if (!task.Wait(PerRequestTimeoutMs)) { var ex = new TaskCanceledException( string.Format("Get file status operation did not complete after {0} milliseconds.", PerRequestTimeoutMs)); TracingHelper.LogError(ex); throw ex; } var fileInfoResponse = task.Result; stopWatch.Stop(); TracingHelper.LogInfo("Op:GETFILESTATUS,Path:{0},IsDirectory,TimeMs:{1}", streamPath, stopWatch.ElapsedMilliseconds); return(fileInfoResponse.FileStatus.Type.GetValueOrDefault() == FileType.DIRECTORY); }
/// <summary> /// Gets a value indicating the length of a stream, in bytes. /// </summary> /// <param name="streamPath">The relative path to the stream.</param> /// <param name="isDownload">if set to <c>true</c> [is download], meaning we will get the stream length on the local machine instead of on the server.</param> /// <returns> /// The length of the stream, in bytes. /// </returns> /// <exception cref="System.Threading.Tasks.TaskCanceledException"></exception> public long GetStreamLength(string streamPath, bool isDownload = false) { if (isDownload) { return(new FileInfo(streamPath).Length); } else { var stopWatch = new Stopwatch(); stopWatch.Start(); var task = _client.FileSystem.GetFileStatusAsync(_accountName, streamPath, cancellationToken: _token); if (!task.Wait(PerRequestTimeoutMs)) { var ex = new TaskCanceledException( string.Format("Get file status operation did not complete after {0} milliseconds.", PerRequestTimeoutMs)); TracingHelper.LogError(ex); throw ex; } var fileInfoResponse = task.Result; stopWatch.Stop(); TracingHelper.LogInfo("Op:GETFILESTATUS,Path:{0},GetLength,TimeMs:{1}", streamPath, stopWatch.ElapsedMilliseconds); return((long)fileInfoResponse.FileStatus.Length); } }
public async Task Enqueue_Func_T_Should_Cancel_Task_When_On_Disposed_Queue() { MonoThreadedQueue queue = null; //arrange using (queue = new MonoThreadedQueue()) { var task = queue.Enqueue(() => TaskFactory()); } Func <int> func = () => { return(25); }; Task newesttask = queue.Enqueue(func); TaskCanceledException error = null; try { await newesttask; } catch (TaskCanceledException e) { error = e; } newesttask.IsCanceled.Should().BeTrue(); error.Should().NotBeNull(); }
private void HandleException(UcwaAppOperationResult result) { switch (result.StatusCode) { case HttpStatusCode.RequestTimeout: // request timed out, may need to readjust the default timeout value TaskCanceledException tcex = result.Exception as TaskCanceledException; ReportError(tcex.Message); break; case HttpStatusCode.Conflict: // duped ack Ids ReportError(result.StatusCode.ToString()); break; case HttpStatusCode.NotFound: // app not exists on server ReportError(result.StatusCode.ToString()); break; default: ReportError(result.Exception.Message); break; } this.Stop(); }
public async Task Actor_Should_Return_Cancelled_Task_On_Any_Method_AfterCalling_IAsyncDisposable_DisposeAsync() { //arrange var dispclass = new DisposableClass(); var intface = _TaskPoolActorFactory.Build <IDummyInterface1>(dispclass); //act var task = intface.DoAsync(); var disp = GetFiber(intface) as IAsyncDisposable; await disp.DisposeAsync(); TaskCanceledException error = null; Task canc = null; try { canc = intface.DoAsync(); await canc; } catch (TaskCanceledException e) { error = e; } //assert error.Should().NotBeNull(); task.IsCompleted.Should().BeTrue(); canc.IsCanceled.Should().BeTrue(); }
public async Task ExecuteCancelableCommand_ThrowsWrappedException() { using (CancellationTokenSource cts = new()) { CancellationCommand command = new(); cts.Cancel(); CommandCanceledException exception = await Assert.ThrowsAsync <CommandCanceledException>(() => CommandExecutor.InvokeAsync(command, cts.Token)); OperationCanceledException inner = Assert.IsType <OperationCanceledException>(exception.InnerException); Assert.Equal(cts.Token, inner.CancellationToken); } using (CancellationTokenSource cts = new()) { CancelCommand command = new(); cts.Cancel(); Task <CommandResult> task = CommandExecutor.InvokeAsync(command, cts.Token); CommandCanceledException exception = await Assert.ThrowsAsync <CommandCanceledException>(() => task); TaskCanceledException inner = Assert.IsType <TaskCanceledException>(exception.InnerException); Assert.Equal(cts.Token, inner.CancellationToken); Assert.NotSame(task, inner.Task); Assert.Equal(TaskStatus.Faulted, task.Status); Assert.Same(exception, task.Exception.InnerExceptions.Single()); } }
/// <summary> /// Deletes an existing stream at the given path. /// </summary> /// <param name="streamPath">The relative path to the stream.</param> /// <param name="recurse">if set to <c>true</c> [recurse]. This is used for folder streams only.</param> /// <param name="isDownload">if set to <c>true</c> [is download], meaning we will delete a stream on the local machine instead of on the server.</param> /// <exception cref="System.Threading.Tasks.TaskCanceledException"></exception> public void DeleteStream(string streamPath, bool recurse = false, bool isDownload = false) { if (isDownload) { if (Directory.Exists(streamPath)) { Directory.Delete(streamPath, recurse); } else if (File.Exists(streamPath)) { File.Delete(streamPath); } } else { var stopWatch = new Stopwatch(); stopWatch.Start(); var task = _client.FileSystem.DeleteAsync(_accountName, streamPath, recurse, cancellationToken: _token); if (!task.Wait(PerRequestTimeoutMs)) { var ex = new TaskCanceledException(string.Format("Delete stream operation did not complete after {0} milliseconds.", PerRequestTimeoutMs)); TracingHelper.LogError(ex); throw ex; } task.GetAwaiter().GetResult(); stopWatch.Stop(); TracingHelper.LogInfo("Op:DELETE,Path:{0},recurse:{1},TimeMs:{2}", streamPath, recurse, stopWatch.ElapsedMilliseconds); } }
public async Task Enqueue_Action_Should_Cancel_Not_Started_Task_When_OnDispose() { Task newTask = null, notstarted = null; var done = false; //arrange var target = GetSafeFiber(t => t.Priority = ThreadPriority.Highest); newTask = target.Enqueue(() => TaskFactory(3)); while (RunningThread == null) { Thread.Sleep(100); } await target.DisposeAsync(); notstarted = target.Enqueue(() => { done = true; }); await newTask; TaskCanceledException error = null; try { await notstarted; } catch (TaskCanceledException e) { error = e; } notstarted.IsCanceled.Should().BeTrue(); error.Should().NotBeNull(); done.Should().BeFalse(); }
/// <summary> /// This methods deals with the situtaion described in /// https://github.com/OctopusDeploy/Issues/issues/4408 /// </summary> /// <param name="ex">The exception to extract details from</param> public void HandleException(TaskCanceledException ex) { ex?.Task?.Exception?.InnerExceptions? .Select(inner => inner.ToString()) .Aggregate("", (message, exMessage) => message + "\n" + exMessage) .Tee(Log.Error); }
public async Task ThrowsAsync_SynchronousTaskThrowsDerivedException_ReturnsException() { var expectedException = new TaskCanceledException(); var result = await AsyncAssert.ThrowsAsync <OperationCanceledException>(Task.FromException(expectedException)); Assert.Same(expectedException, result); }
public void Update(TaskCanceledException ex) { Exception = ex; HttpStatusCode = System.Net.HttpStatusCode.RequestTimeout; Debug.WriteLine($"{DateTime.Now.TimeOfDay} Timeout {ex.Message}"); ReturnResult = ResponseResult.Timeout; }
private void VerifyTaskCanceledException(TaskInfo current) { bool expCaught; TaskInfo ti = current; //a task will get into cancelled state only if: //1.Its token was cancelled before as its action to get invoked //2.The token was cancelled before the task's action to finish, task observed the cancelled token and threw OCE(token) if (ti.Task.Status == TaskStatus.Canceled) { expCaught = FindException((ex) => { TaskCanceledException expectedExp = ex as TaskCanceledException; return(expectedExp != null && expectedExp.Task == ti.Task); }); Assert.True(expCaught, "expected TaskCanceledException in Task.Name = Task " + current.Name + " NOT caught"); } else { expCaught = FindException((ex) => { TaskCanceledException expectedExp = ex as TaskCanceledException; return(expectedExp != null && expectedExp.Task == ti.Task); }); Assert.False(expCaught, "NON-expected TaskCanceledException in Task.Name = Task " + current.Name + " caught"); } }
public async Task CanDestructureTaskAsync() { using var cancellationTokenSource = new CancellationTokenSource(0); TaskCanceledException exception = null; try { await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false); } catch (TaskCanceledException taskCancelledException) { exception = taskCancelledException; } var propertiesBag = new ExceptionPropertiesBag(exception); CreateReflectionBasedDestructurer().Destructure(exception, propertiesBag, EmptyDestructurer()); var properties = propertiesBag.GetResultDictionary(); var destructuredTaskObject = (IDictionary)properties[nameof(TaskCanceledException.Task)]; var destructuredTaskProperties = Assert.IsAssignableFrom <IDictionary <string, object> >(destructuredTaskObject); destructuredTaskProperties.Should().ContainKey(nameof(Task.Id)); destructuredTaskProperties.Should().ContainKey(nameof(Task.Status)) .WhichValue.Should().BeOfType <string>() .Which.Should().Be(nameof(TaskStatus.Canceled)); destructuredTaskProperties.Should().ContainKey(nameof(Task.CreationOptions)) .WhichValue.Should().BeOfType <string>() .Which.Should().Contain(nameof(TaskCreationOptions.None)); }
public async Task Actor_IActorLifeCycle_Abort_Should_Cancel_Enqueued_Task() { //arrange var dispclass = new DisposableClass(); var intface = _Factory.Build <IDummyInterface1>(dispclass); Task Taskrunning = intface.DoAsync(), Takenqueued = intface.DoAsync(); Thread.Sleep(100); //act IActorCompleteLifeCycle disp = intface as IActorCompleteLifeCycle; await disp.Abort(); //assert TaskCanceledException error = null; try { await Takenqueued; } catch (TaskCanceledException e) { error = e; } //assert error.Should().NotBeNull(); Takenqueued.IsCanceled.Should().BeTrue(); }
public async Task SupportsCooperativeCancellation() { using (CancellationTokenSource cts = new()) { CommandBase command = new CancellationCommand(); cts.Cancel(); OperationCanceledException exception = await Assert.ThrowsAsync <OperationCanceledException>(() => command.ExecuteAsync(cts.Token)); Assert.Equal(cts.Token, exception.CancellationToken); } using (CancellationTokenSource cts = new()) { CommandBase command = new CancelCommand(); cts.Cancel(); Task <CommandResult> task = command.ExecuteAsync(cts.Token); TaskCanceledException exception = await Assert.ThrowsAsync <TaskCanceledException>(() => task); Assert.Equal(cts.Token, exception.CancellationToken); Assert.Same(task, exception.Task); Assert.Equal(TaskStatus.Canceled, task.Status); Assert.Null(task.Exception); } }
public static async Task SendMailAsync( this SmtpClient client, MailMessage message, CancellationToken cancellationToken) { var ctsWrapper = new[] { cancellationToken.CreateLinkedSource() }; var mailSent = false; Exception?exception = null; void onCompleted(object sender, AsyncCompletedEventArgs e) { if (e.Cancelled) { exception = new TaskCanceledException(); } if (e.Error != null) { exception = e.Error; } mailSent = true; ctsWrapper[0].Cancel(); }; client.SendCompleted += onCompleted; client.SendAsync(message, new object()); try { await Task.Delay(Timeout.InfiniteTimeSpan, ctsWrapper[0].Token); } catch (TaskCanceledException) { // no throw for canceled delay } if (!mailSent) { ctsWrapper[0] = new CancellationTokenSource(); client.SendAsyncCancel(); try { await Task.Delay(TimeSpan.FromSeconds(1), ctsWrapper[0].Token); Debug.Fail(string.Empty); throw new InvalidOperationException(); } catch (TaskCanceledException) { // no throw for canceled delay } } client.SendCompleted -= onCompleted; if (exception != null) { throw exception; } }
public async Task CancelsAsync_SynchronousTaskCancelsWithDerivedException_ReturnsException() { var expectedException = new TaskCanceledException(); var result = await AsyncAssert.CancelsAsync(Task.FromException(expectedException)); Assert.Same(expectedException, result); }
public void PolicyCallsTheLoggerIfPolicyHandlesException() { ILogger expectedLogger = new StubLogger(); Func <Context, ILogger> loggerProvider = _ => expectedLogger; ILogger invokedLogger = null; Exception exceptionInvokedFor = null; HttpStatusCode?resultInvokedFor = null; Action <ILogger, Context, DelegateResult <HttpStatusCode> > logAction = (logger, context, outcome) => { invokedLogger = logger; exceptionInvokedFor = outcome.Exception; resultInvokedFor = outcome.Result; }; AsyncLoggingPolicy <HttpStatusCode> policy = Policy <HttpStatusCode> .Handle <TaskCanceledException>() .OrResult(r => r != HttpStatusCode.OK) .AsyncLog(loggerProvider, logAction); var thrownException = new TaskCanceledException(); policy.Awaiting(p => p.ExecuteAsync(() => throw thrownException)).ShouldThrow <TaskCanceledException>(); invokedLogger.Should().Be(expectedLogger); exceptionInvokedFor.Should().Be(thrownException); resultInvokedFor.Should().Be(default(HttpStatusCode)); }
public void Cancels_DelegateCancelsWithDerivedException_ReturnsException() { var expectedException = new TaskCanceledException(); var result = AsyncAssert.Cancels(() => { throw expectedException; }); Assert.Same(expectedException, result); }
public async Task SendAsync_ClientTimeout() { using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost")) { this.httpClient.Dispose(); var clientException = new TaskCanceledException(); this.httpClient = new HttpClient(new ExceptionHttpMessageHandler(clientException), /* disposeHandler */ true); this.httpProvider.httpClient = this.httpClient; try { await this.httpProvider.SendRequestAsync(httpRequestMessage); } catch (OneDriveException exception) { Assert.IsNotNull(exception.Error, "No error body returned."); Assert.AreEqual(OneDriveErrorCode.Timeout.ToString(), exception.Error.Code, "Incorrect error code returned."); Assert.AreEqual("The request timed out.", exception.Error.Message, "Unexpected error message."); Assert.AreEqual(clientException, exception.InnerException, "Inner exception not set."); throw; } } }
public void TypePropertiesAreCorrect() { Assert.AreEqual(typeof(TaskCanceledException).GetClassName(), "Bridge.TaskCanceledException", "Name"); object d = new TaskCanceledException(); Assert.True(d is TaskCanceledException, "is TaskCanceledException"); Assert.True(d is OperationCanceledException, "is OperationCanceledException"); Assert.True(d is Exception, "is Exception"); }
private void LogCancelled(TaskCanceledException ex) { using (var scope = _serviceScopeFactory.CreateScope()) { var logger = scope.ServiceProvider.GetService <ILogger>(); logger.Information("TaskScheduler - zadanie zostało przerwane", new { type = typeof(T).FullName, exception = ex }); } }
private void ProcessTaskCanceledException(TaskCanceledException ex) { if (ex.CancellationToken != null && !ex.CancellationToken.IsCancellationRequested) { throw new TimeoutException("A task was canceled because of timeout expiration.", ex); } throw ex; }
public void TypePropertiesAreCorrect() { Assert.AreEqual("Bridge.TaskCanceledException", typeof(TaskCanceledException).GetClassName(), "Name"); object d = new TaskCanceledException(); Assert.True(d is TaskCanceledException, "is TaskCanceledException"); Assert.True(d is OperationCanceledException, "is OperationCanceledException"); Assert.True(d is Exception, "is Exception"); }
public void MessageOnlyConstructorWorks() { var ex = new TaskCanceledException("Some message"); Assert.True((object)ex is TaskCanceledException, "is TaskCanceledException"); Assert.AreEqual(ex.Message, "Some message", "Message"); Assert.Null(ex.Task, "Task"); Assert.True(ReferenceEquals(ex.CancellationToken, CancellationToken.None), "CancellationToken"); Assert.Null(ex.InnerException, "InnerException"); }
private static string GetCancelledErrorMsg(CommandDefinition cmd, TaskCanceledException ex = null) { return ($"* Canceled Error CMD:{cmd.CommandText} " + $"PARAMS:{cmd.Parameters} " + $"TIMEOUT:{cmd.CommandTimeout} " + $"TOKEN:{cmd.CancellationToken.IsCancellationRequested} " + $"EX:{GetInnerEx(ex)} "); }
public void TypePropertiesAreCorrect() { Assert.AreEqual("System.Threading.Tasks.TaskCanceledException", typeof(TaskCanceledException).FullName, "Name"); object d = new TaskCanceledException(); Assert.True(d is TaskCanceledException, "is TaskCanceledException"); Assert.True(d is OperationCanceledException, "is OperationCanceledException"); Assert.True(d is Exception, "is Exception"); }
public void TaskOnlyConstructorWorks() { var task = new TaskCompletionSource<int>().Task; var ex = new TaskCanceledException(task); Assert.True((object)ex is TaskCanceledException, "is TaskCanceledException"); Assert.AreEqual(ex.Message, "A task was canceled.", "Message"); Assert.True(ReferenceEquals(ex.Task, task), "Task"); Assert.True(ReferenceEquals(ex.CancellationToken, CancellationToken.None), "CancellationToken"); Assert.Null(ex.InnerException, "InnerException"); }
public async Task CancelDuringGetDownloadStream() { var package = new FakeDataServicePackage(new Uri("http://example.com/packages/Foo/1.0")); packagePathResolver.Setup(r => r.GetInstallPath(package)).Returns("Foo"); packagePathResolver.Setup(r => r.GetPackageFileName(package)).Returns("Foo.1.0.nupkg"); var insideHandlerSignal = new ManualResetEventSlim(initialState: false); var proceedFromHandlerSignal = new ManualResetEventSlim(initialState: false); var exception = new TaskCanceledException("Fake"); repository.MessageHandler = new FakeHttpMessageHandler((req, token) => { insideHandlerSignal.Set(); Assert.True(proceedFromHandlerSignal.Wait(TimeSpan.FromMilliseconds(500)), "Timeout waiting for proceedFromHandlerSignal"); if (token.IsCancellationRequested) { throw exception; } }); var cts = new CancellationTokenSource(); var cancelTask = Task.Run(() => { Assert.True(insideHandlerSignal.Wait(TimeSpan.FromMilliseconds(500)), "Timeout waiting for MessageHandler.SendAsync"); cts.Cancel(); proceedFromHandlerSignal.Set(); }); try { await repository.AddPackageAsync(package, cts.Token); await cancelTask; Assert.Fail("Expected TaskCanceledException"); } catch (TaskCanceledException ex) { Assert.That(ex, Is.SameAs(exception), "Expected spcific instance of TaskCanceledException"); } }
public async Task CloudFileUploadCancellationAsync() { CloudFileShare share = DefaultFileClient.GetShareReference(Guid.NewGuid().ToString("N")); byte[] buffer = FileTestBase.GetRandomBuffer(4 * 1024 * 1024); try { await share.CreateAsync(); CloudFile file = share.GetRootDirectoryReference().GetFileReference("file1"); FileRequestOptions requestOptions = new FileRequestOptions() { RetryPolicy = new NoRetry() }; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; new Task(() => { new System.Threading.ManualResetEvent(false).WaitOne(100); cts.Cancel(false); }).Start(); using (MemoryStream ms = new MemoryStream(buffer)) { file.UploadFromStreamAsync(ms.AsInputStream(), null, requestOptions, null).AsTask(token).Wait(); } Assert.Fail(); } catch (AggregateException e) { TaskCanceledException ex = new TaskCanceledException(); Assert.AreEqual(ex.HResult, e.InnerException.HResult); } finally { share.DeleteIfExistsAsync().AsTask().Wait(); } }
public static void RunTaskCanceledExceptionTests() { TaskCanceledException tce = null; // Test empty constructor tce = new TaskCanceledException(); Assert.Null(tce.Task); // , "RunTaskCanceledExceptionTests: Expected null Task prop after empty ctor") Assert.Null(tce.InnerException); // , "RunTaskCanceledExceptionTests: Expected null InnerException prop after empty ctor") string message = "my exception message"; tce = new TaskCanceledException(message); Assert.True(tce.Message.Equals(message), "RunTaskCanceledExceptionTests: Message != string passed to ctor(string)"); Assert.Null(tce.Task); // , "RunTaskCanceledExceptionTests: Expected null Task prop after ctor(string)") Assert.Null(tce.InnerException); // , "RunTaskCanceledExceptionTests: Expected null InnerException prop after ctor(string)") Task t1 = Task.Factory.StartNew(() => { }); tce = new TaskCanceledException(t1); Assert.True(tce.Task == t1, "RunTaskCanceledExceptionTests: Task != task passed to ctor(Task)"); Assert.Null(tce.InnerException); // , "RunTaskCanceledExceptionTests: Expected null InnerException prop after ctor(Task)") InvalidOperationException ioe = new InvalidOperationException(); tce = new TaskCanceledException(message, ioe); Assert.True(tce.Message.Equals(message), "RunTaskCanceledExceptionTests: Message != string passed to ctor(string, exception)"); Assert.Null(tce.Task); // , "RunTaskCanceledExceptionTests: Expected null Task prop after ctor(string, exception)") Assert.True(tce.InnerException == ioe, "RunTaskCanceledExceptionTests: InnerException != exception passed to ctor(string, exception)"); }
public async Task CloudBlobUploadCancellationAsync() { CloudBlobContainer container = DefaultBlobClient.GetContainerReference(Guid.NewGuid().ToString("N")); byte[] buffer = BlobTestBase.GetRandomBuffer(4 * 1024 * 1024); try { await container.CreateAsync(); CloudBlockBlob blob = container.GetBlockBlobReference("blob1"); BlobRequestOptions requestOptions = new BlobRequestOptions() { RetryPolicy = new NoRetry() }; CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; new Task(() => { new System.Threading.ManualResetEvent(false).WaitOne(500); cts.Cancel(false); }).Start(); using (MemoryStream ms = new MemoryStream(buffer)) { blob.UploadFromStreamAsync(ms.AsInputStream(), null, requestOptions, null).AsTask(token).Wait(); } Assert.Fail(); } catch (AggregateException e) { TaskCanceledException ex = new TaskCanceledException(); Assert.AreEqual(ex.HResult, e.InnerException.HResult); } finally { container.DeleteIfExistsAsync().AsTask().Wait(); } }
internal void Execute() { CreateEnvironment(); _completedSynchronouslyThreadId = Thread.CurrentThread.ManagedThreadId; try { _appContext.AppFunc(_env) // We can't use Then/Catch here because they would re-enter the sync context. // The async callback must be called outside of the sync context. .ContinueWith(appTask => { if (appTask.IsFaulted) { if (!TryRelayExceptionToIntegratedPipeline(false, appTask.Exception)) { Complete(ErrorState.Capture(appTask.Exception)); } } else if (appTask.IsCanceled) { Exception ex = new TaskCanceledException(appTask); if (!TryRelayExceptionToIntegratedPipeline(false, ex)) { Complete(ErrorState.Capture(ex)); } } else { OnEnd(); } }); } catch (Exception) { throw; } finally { _completedSynchronouslyThreadId = Int32.MinValue; } }
private Exception GetTaskException(Task task) { Exception exception = task.Exception; if (exception != null) { return exception.InnerException; } if (!task.IsCanceled) { return null; } exception = new TaskCanceledException(task); try { MethodInfo info = task.GetType().GetMethod("GetCancellationExceptionDispatchInfo", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null); if (info == null) { return exception; } object obj2 = info.Invoke(task, null); if (obj2 == null) { return exception; } MethodInfo info2 = obj2.GetType().GetMethod("Throw", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, null, new Type[0], null); if (info2 == null) { return exception; } try { info2.Invoke(obj2, null); } catch (Exception exception3) { return exception3; } } catch { } return exception; }