cancellationtokensource

How do you catch CancellationToken.Register callback exceptions?

天涯浪子 提交于 2019-11-28 20:52:30
I am using async I/O to communicate with an HID device, and I would like to throw a catchable exception when there is a timeout. I've got the following read method: public async Task<int> 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 t; return t.Result; } catch( Exception ex ) { Debug.WriteLine( "exception" ); return 0; } } } The exception

Using CancellationToken for timeout in Task.Run does not work

∥☆過路亽.° 提交于 2019-11-28 20:14:37
OK, my questions is really simple. Why this code does not throw TaskCancelledException ? static void Main() { var v = Task.Run(() => { Thread.Sleep(1000); return 10; }, new CancellationTokenSource(500).Token).Result; Console.WriteLine(v); // this outputs 10 - instead of throwing error. Console.Read(); } But this one works static void Main() { var v = Task.Run(() => { Thread.Sleep(1000); return 10; }, new CancellationToken(true).Token).Result; Console.WriteLine(v); // this one throws Console.Read(); } Cancellation in Managed Threads : Cancellation is cooperative and is not forced on the

Difference between CancellationTokenSource and exit flag for Task loop exit

家住魔仙堡 提交于 2019-11-28 11:09:47
I was wondering if there is any difference between ending loop task with CancellationTokenSource and exit flag CancellationTokenSource: CancellationTokenSource cancellationTokenSource; Task loopTask; void StartLoop() { cancellationTokenSource = new CancellationTokenSource(); loopTask = Task.Factory.StartNew(Loop, TaskCreationOptions.LongRunning); } void Loop() { while (true) { if (cancellationTokenSource.IsCancellationRequested) break; Thread.Yield(); } } void StopLoop() { cancellationTokenSource.Cancel(); loopTask = null; cancellationTokenSource = null; } Exit flag: volatile bool exitLoop;

Why is the task is not cancelled when I call CancellationTokenSource's Cancel method in async method?

五迷三道 提交于 2019-11-28 08:13:32
问题 I created a small wrapper around CancellationToken and CancellationTokenSource . The problem I have is that the CancelAsync method of CancellationHelper doesn't work as expected. I'm experiencing the problem with the ItShouldThrowAExceptionButStallsInstead method. To cancel the running task, it calls await coordinator.CancelAsync(); , but the task is not cancelled actually and doesn't throw an exception on task.Wait ItWorksWellAndThrowsException seems to be working well and it uses

How do I reset a CancellationToken properly?

对着背影说爱祢 提交于 2019-11-28 08:01:55
I have been playing round with the async ctp this morning and have a simple program with a button and a label . Click the button and it starts updating the label , stop the button it stops writing to the label . However, I'm not sure how to reset the CancellationTokenSource so that I can restart the process. My code is below: public partial class MainWindow : Window { CancellationTokenSource cts = new CancellationTokenSource(); public MainWindow() { InitializeComponent(); button.Content = "Start"; } async Task DoWork(CancellationToken cancelToken) { int i = 0; while (!cancelToken

How to cancel an async WCF call?

怎甘沉沦 提交于 2019-11-28 05:49:12
问题 I have been trying some time to find out how to implement WCF call cancellation based on the new .NET 4.5 CancellationToken mechanism. All the samples I found are not WCF based, and do not cross the service boundary. My service : [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] public class MyService : IMyService { public void LongOperation() { // do stuff that takes ages... // please cancel me! } } My Client (Desktop App): Using an auto generated proxy : private async

Why CancellationToken is separate from CancellationTokenSource?

[亡魂溺海] 提交于 2019-11-28 03:10:23
I'm looking for a rationale of why .NET CancellationToken struct was introduced in addition to CancellationTokenSource class. I understand how the API is to be used, but want to also understand why it is designed that way. I.e., why do we have: var cts = new CancellationTokenSource(); SomeCancellableOperation(cts.Token); ... public void SomeCancellableOperation(CancellationToken token) { ... token.ThrowIfCancellationRequested(); ... } instead of directly passing CancellationTokenSource around like: var cts = new CancellationTokenSource(); SomeCancellableOperation(cts); ... public void

Canceling SQL Server query with CancellationToken

五迷三道 提交于 2019-11-27 22:57:01
I have a long-running stored procedure in SQL Server that my users need to be able to cancel. I have written a small test app as follows that demonstrates that the SqlCommand.Cancel() method works quite nicely: 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.

How do you catch CancellationToken.Register callback exceptions?

妖精的绣舞 提交于 2019-11-27 13:16:42
问题 I am using async I/O to communicate with an HID device, and I would like to throw a catchable exception when there is a timeout. I've got the following read method: public async Task<int> 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 t;

Cancelling an HttpClient Request - Why is TaskCanceledException.CancellationToken.IsCancellationRequested false?

核能气质少年 提交于 2019-11-27 12:40:29
Given the following code: 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 to exception"); } I would expect ex