0

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.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
  • Are you trying to run the taks in parallel? – Poul Bak May 28 '23 at 20:53
  • 1
    Are you trying to create a cache? If yes, you might find [this](https://stackoverflow.com/questions/28340177/enforce-an-async-method-to-be-called-once) question interesting, or [this](https://stackoverflow.com/questions/54117652/concurrentdictionary-getoradd-async). – Theodor Zoulias May 28 '23 at 22:20
  • 1
    Thanks for specify the aswered question because I can't found it. At least I was not very lost when I tryped the Unwrap method, but I was trying to start the unwraped task insted the internal task before unwraped. – Asier Cayón Francisco May 29 '23 at 00:14

0 Answers0