Reputation: 127
I want to create some async Tasks without starting them at the moment. With the untyped Tasks there is no problem:
private Task CreateTask() {
return new Task(
async () => await DoSomething().ConfigureAwait(false));
}
But to handle Exceptions I added a return value to my function. But how can I write it in a correct syntax:
private Task<bool> CreateTask() {
return new Task<bool>(
async () => await DoSomething().ConfigureAwait(false));
}
I get the message, that the async lambda expression can't be converted to func. So my question: How is it written correctly?
Upvotes: 4
Views: 282
Reputation: 456507
I want to create some async Tasks without starting them at the moment.
That is the wrong solution for whatever problem you're trying to solve. If you want to define code that you want to run in the future, then you should use a delegate:
private Func<Task> CreateTaskFactory()
{
return async () => await DoSomething().ConfigureAwait(false);
}
But to handle Exceptions I added a return value to my function.
Again, that's not the best solution. Tasks already understand exceptions just fine without writing any additional code.
If you do need to return a value (as data), then you can return a delegate that creates a Task<T>
:
private Func<Task<int>> CreateTaskFactory()
{
return async () => await DoSomethingReturningInt().ConfigureAwait(false);
}
Upvotes: 3