-
January 14th, 2014, 10:06 AM
#1
Continuation tasks
Given following
Code:
static void Main(string[] args)
{
try
{
CancellationTokenSource cts = new CancellationTokenSource();
Task t = Task.Factory.StartNew(() => MyCanceledMethod(cts.Token), cts.Token);
t.ContinueWith(x =>
{
Console.WriteLine("Canceled successfully !");
}, TaskContinuationOptions.OnlyOnCanceled);
cts.Cancel();
t.Wait();
}
catch { }
}
static void MyCanceledMethod(CancellationToken ct)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
Console.Write('*');
}
}
No problem ! The task running MyCanceledMethod is perfectly canceled and I don't get to see the *****.
Now if I were to start the task in this way
Task t = Task.Factory.StartNew(x => MyCanceledMethod(cts.Token), cts.Token);
That's with a lambda taking one not used parameter x instead of () , the task just doesn't get canceled
Can anyone explain to me the relation between task delegate signature and the TaskContinuationOptions.OnlyOnCanceled not being respected ?
-
January 14th, 2014, 12:22 PM
#2
Re: Continuation tasks
That looks like what you have posted above. Mistake on your part?
Here's a link, btw. http://msdn.microsoft.com/en-us/libr...vs.110%29.aspx
-
January 14th, 2014, 01:58 PM
#3
Re: Continuation tasks
No mistake ! Please note the x as a parameter to the delegate in the 2nd way of starting the task.
-
January 15th, 2014, 02:36 AM
#4
Re: Continuation tasks
You have the same line in both places Task t= ...
-
January 15th, 2014, 03:43 AM
#5
Re: Continuation tasks
No, it's different ! And meanwhile I found out what's causing the different behavior.
My first way of starting the task, note the '() =>'
Code:
Task t = Task.Factory.StartNew(() => MyCanceledMethod(cts.Token), cts.Token);
This is actually using following overload of StartNew method, allowing perfect cancelling of MyCanceledMethod
Code:
public Task StartNew(Action action, CancellationToken cancellationToken)
My second way of starting the task, please note the 'x =>'
Code:
Task t = Task.Factory.StartNew(x => MyCanceledMethod(cts.Token), cts.Token);
comes down to this overload of StartNew that simply casts the CancellationToken to object
Code:
public Task StartNew(Action<Object> action, Object state)
It's a subtle difference, but kind a hard to discover with such extensively overloaded methods !
-
January 15th, 2014, 11:00 AM
#6
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|