Tag: cancellationtokensource

你如何捕获CancellationToken.Register回调exception?

我使用异步I / O与HID设备通信,我想在超时时抛出一个可捕获的exception。 我有以下读取方法: public async Task Read( byte[] buffer, int? size=null ) { size = size ?? buffer.Length; using( var cts = new CancellationTokenSource() ) { cts.CancelAfter( 1000 ); cts.Token.Register( () => { throw new TimeoutException( “read timeout” ); }, true ); try { var t = stream.ReadAsync( buffer, 0, size.Value, cts.Token ); await […]

使用CancellationToken取消SQL Server查询

我在SQL Server中有一个长时间运行的存储过程,我的用户需要能够取消它。 我编写了一个如下的小测试应用程序,它演示了SqlCommand.Cancel()方法非常好用: private SqlCommand cmd; private void TestSqlServerCancelSprocExecution() { TaskFactory f = new TaskFactory(); f.StartNew(() => { using (SqlConnection conn = new SqlConnection(“connStr”)) { conn.InfoMessage += conn_InfoMessage; conn.FireInfoMessageEventOnUserErrors = true; conn.Open(); cmd = conn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = “dbo.[CancelSprocTest]”; cmd.ExecuteNonQuery(); } }); } private void cancelButton_Click(object sender, EventArgs e) { if (cmd != […]

取消HttpClient请求 – 为什么TaskCanceledException.CancellationToken.IsCancellationRequested为false?

给出以下代码: var cts = new CancellationTokenSource(); try { // get a “hot” task var task = new HttpClient().GetAsync(“http://www.google.com”, cts.Token); // request cancellation cts.Cancel(); await task; // pass: Assert.Fail(“expected TaskCanceledException to be thrown”); } catch (TaskCanceledException ex) { // pass: Assert.IsTrue(cts.Token.IsCancellationRequested, “expected cancellation requested on original token”); // fail: Assert.IsTrue(ex.CancellationToken.IsCancellationRequested, “expected cancellation requested on token attached […]