Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a Task in a dictionary for later execution in C#

I'm trying to store a Task in a dictionary for later execution with no success:

Dictionary<string, Task<object>> router = new Dictionary<string, Task<object>();
router["xyz"] = functionToLaterExec

async Task<string> functionToLaterExec()
{
    return await Task.FromResult("Success!");
} 

If I declare the function as

string functionToExec()

Then I can do:

router["xyz"] = new Task<string>(functionToExec);

But I need the function to be async. And don't know how to invoke it. I've tryed:

var t = router["xyz"];
var data = Encoding.UTF8.GetBytes(await t);

with no success.

Thanks.

like image 382
mattinsalto Avatar asked Nov 07 '16 16:11

mattinsalto


People also ask

Can dictionary store different data types?

One can only put one type of object into a dictionary. If one wants to put a variety of types of data into the same dictionary, e.g. for configuration information or other common data stores, the superclass of all possible held data types must be used to define the dictionary.

How do I wait until Task is finished in C#?

The Task. WaitAll() method in C# is used to wait for the completion of all the objects of the Task class. The Task class represents an asynchronous task in C#. We can start threads with the Task class and wait for the threads to finish with the Task.

Can we store anything other than string or INT in dictionary key?

You can use a Dictionary<string,object> and then you can put anything you want into it.

What is a Task in c sharp?

A task in C# is used to implement Task-based Asynchronous Programming and was introduced with the . NET Framework 4. The Task object is typically executed asynchronously on a thread pool thread rather than synchronously on the main thread of the application.


1 Answers

If you want to be able to start an asynchronous operation later then you don't want to store a Task, you'll want to store a Func<Task> (or, in your case, a Func<Task<string>>, so that, when you want to start the operation, you can invoke the function, producing a Task that represents its completion.

like image 121
Servy Avatar answered Sep 26 '22 14:09

Servy