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.
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.
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.
You can use a Dictionary<string,object> and then you can put anything you want into it.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With