I would like to create a Task
that calls an async method with await
keyword, then add into a control dictionary and after this run the task.
I was able to create the Task and start it using both, Task.Factory.StartNew
and Task.Run
method, but doing this the task starts before I was able to add into a dictionary.
The next code shows 4 examples tasks. The task1
shows what I need but without a async/await call inside of a task. The task2
and the task3
shows what I want to do with a task but starts the task before add into a dictionary. The task4
, doesn't compile, but shows what I would like to get it:
public Task<int> Dummy()
{
return Task.FromResult(0);
}
Dictionary<string, Task> TaskController = new Dictionary<string, Task>();
public async Task LoadData()
{
Task<int> task1 = new Task<int>(() => 0);
TaskController.Add("a", task1);
task1.Start();
await task1;
TaskController.Remove("a");
Task<int> task2;
task2 = await Task.Factory.StartNew<Task<int>>(async () => await Dummy());
TaskController.Add("b", task2);
//task2.Start();
await task2;
TaskController.Remove("b");
Task<int> task3;
task3 = Task.Run<int>(async () => await Dummy());
TaskController.Add("b", task3);
//task3.Start();
await task3;
TaskController.Remove("b");
//I would like to to this
Task<int> task4;
task4 = new Task<int>(async => await Dummy());
TaskController.Add("b", task4);
task4.Start();
await task4;
TaskController.Remove("b");
}
Is there any way to do this or it was not possible?
NOTE:
I was trying with the TaskExtensions.Unwrap
extension method but I suspect that it also runs the task before.