Using Tasks: ContinueWith requires a return statement which doesn't require my business logic
I started using Tasks yesterday for a small project of mine. After setting up the task logic in the code, I realized that I had to use a return statement in my ContinueWith () function.
Is there a way to avoid returning inside ContinueWith even though it myTask
needs to return an object first?
Task<List<Object>> myTask = Task<List<Object>>.Factory.StartNew(() =>
{
//business logic creating an Object to return
//return Object created
})
.ContinueWith<List<Object>>((antecedant) =>
{
//business logic : needs to use antecedant
return null; //can i get rid of this? I don't need to return an object in this section
}, TaskScheduler.FromCurrentSynchronizationContext());
Let's just say that the return null statement annoys me ...
Note: in response to Yuval's comment, I am using .NET Framework 4.5
Decision
As per CoryNelson's comment, I came up with this code. This suits my needs.
Task<List<Object>> myTask = Task<List<Object>>.Factory.StartNew(() =>
{
//business logic creating an Object to return
//return Object created
});
Task myFollowingTask = myTask.ContinueWith((antecedant) =>
{
//business logic using antecedant
}, TaskScheduler.FromCurrentSynchronizationContext());
I no longer need the return statement in ContinueWith.
Here 's where I went to get the information I needed. See sample code
source to share
Two ways to deal with the problem:
Split the task variable declaration:
Task<List<Object>> myTask = Task<List<Object>>.Factory.StartNew(() =>
{
//business logic creating an Object to return
//return Object created
});
Task taskContinuation = myTask.ContinueWith((antecedant) =>
{
//business logic : needs to use antecedant
}, TaskScheduler.FromCurrentSynchronizationContext());
This will allow you to perform these two tasks regardless of where the continuation
type is Task
.
The second and better approach IMO would be to use async-await
:
public async Task CreateFooAsync()
{
List<object> objects = await Task.Run(() => /* Create object */);
// here you're on the UI thread, continue execution flow as normal.
}
Note that semantics async-await
means that the first task will asynchronously wait for objects to be created.
source to share
If you want to access the result outside of the problem, you will need to feed that result to the output myTask
.
Task<List<Object>> myTask = Task<List<Object>>.Factory.StartNew(() =>
{
//business logic creating an Object to return
//return Object created
})
.ContinueWith((antecedant) =>
{
//business logic : needs to use antecedant
return antecedant.Result;
}, TaskScheduler.FromCurrentSynchronizationContext());
This will make it myTask.Result
look the same as the antecedant.Result
inside ContinueWith
.
source to share