Reputation: 109
i am trying to implement task class in windows phone 8.1 app. In my app the task is to know that whether user has pressed the back key, completed the task or failure occured due to network. for this i am using continue with () method of task class. dont know what the issue. help me in it .
code:
await GetData(limit, offset).ContinueWith(t =>
{
//Console.WriteLine("task completed");
result = t.Result;
//throw new Exception("task 2 error");
}, TaskContinuationOptions.OnlyOnRanToCompletion).ContinueWith(t =>
{
//Console.WriteLine("task fault");
//throw new Exception("task 2 error");
}, TaskContinuationOptions.OnlyOnFaulted).ContinueWith(t =>
{
// Console.WriteLine("task cancelled");
//throw new Exception("task 2 error");
}, TaskContinuationOptions.OnlyOnCanceled);
);
i dont know what's the issue so kindly help required.
Upvotes: 0
Views: 55
Reputation: 4744
Don't use ContinueWith
if you have access to async
/await
. It's that simple. ContinueWith
will let you do all the same things as the new keyword, but is far harder to read, understand, use well and maintain. So do yourself a favor and don't use it unless you really really have to.
Your code becomes
try
{
result = await GetData(limit, offset);
}
catch(TaskCancelledException)
{
// GetData has been cancelled
// Console.WriteLine("task cancelled");
//throw new Exception("task 2 error");
}
catch(Exception)
{
//GetData has been faulted
//Console.WriteLine("task fault");
//throw new Exception("task 2 error");
}
Now it is far easier to understand what you mean to do.
edit
A further clarification seems needed here. Using the await
keywords fundamentally is the same as using ContinueWith
. It just allows you to write complex asynchronous logic in a much more concise and easy to read way.
async Task DoAsyncWork()
{
var a = await GetAAsync();
Frob(a);
}
is exactly the same as
//Notice there is no async keword here
Task DoAsyncWork()
{
return GetAAsync().ContinueWith(t => Frob(t.Result),
TaskContinuationOptions.OnlyOnRanToCompletion);
}
Similarly, a try/catch
block with an await
inside is equivalent to a fairly complicated expression with ContinueWith
, TaskContinuationOptions
and AggregateException
unwrapping.
It gets much more complex if you add the possibility of chaining two or more Tasks
, or some if
here and there, and some loops for good measure (for
, foreach
or while
, it does not really matter). if you stick to your ContinueWith
guns you get the kind of code that no sane man would like to write. And that's ok, because it's the compiler's job to write it for you. And the compiler is not a sane man. So just stick to àwait`as long as you can.
If you can't use async/await
(clearly not your case, you're programming for WP8), it's okay to weep, because you're in for a lot of potential hurt. Some extension methods would make your life easier, but it still won't be pretty.
Upvotes: 2