26

Can someone explain to me how to return the result of a Task? I currently am trying to do the following but my Tasks are not returning my List that I expect? What is the problem here?

static void Main() { List<Task> tasks = new List<Task>(); List<string> sha256_hashes = new List<string>(); List<string> results = new List<string>(); sha256_hashes.Add("hash00"); sha256_hashes.Add("hash01"); sha256_hashes.Add("hash03"); foreach(string sha256 in sha256_hashes) { string _sha256 = sha256; var task = Task.Factory.StartNew(() => GetAdditionalInfo(_sha256)); tasks.Add(task); } Task.WaitAll(tasks.ToArray()); //I want to put all the results of each task from tasks but the problem is //I can't use the Result method from the _task because Result method is not available //below is my plan to get all the results: foreach(var _task in tasks) { if(_task.Result.Count >= 1) //got an error Only assignment, call, increment, dec.... results.AddRange(_task.Result); //got an error Only assignment, call, increment, dec.... } //Do some work about results } static List<string> GetAdditionalInfo(string hash) { //this code returns information about the hash in List of strings } 
2
  • 2
    Task.Result isn't array. Commented Dec 11, 2014 at 17:28
  • 3
    Task doesn't have a Result property - it looks like tasks should have type List<Task<List<string>>> Commented Dec 11, 2014 at 17:30

1 Answer 1

33

To return a result from a Task you need to define the Task as such: Task<TResult> and pass the return type of the result as a generic parameter. (Otherwise the Task will return nothing)

For Example:

 // Return a value type with a lambda expression Task<int> task1 = Task<int>.Factory.StartNew(() => 1); int i = task1.Result; // Return a named reference type with a multi-line statement lambda. Task<Test> task2 = Task<Test>.Factory.StartNew(() => { string s = ".NET"; double d = 4.0; return new Test { Name = s, Number = d }; }); Test test = task2.Result; // Return an array produced by a PLINQ query Task<string[]> task3 = Task<string[]>.Factory.StartNew(() => { string path = @"C:\Users\Public\Pictures\Sample Pictures\"; string[] files = System.IO.Directory.GetFiles(path); var result = (from file in files.AsParallel() let info = new System.IO.FileInfo(file) where info.Extension == ".jpg" select file).ToArray(); return result; }); 

The problem is that you are not specifying that the Task is going to return anything.

You have defined a List of Tasks that do not return anything.

What you will need to do is specify the return type in the Task when you define Task as the generic type for the List in your case. Something like:

var taskLists = new List<Task<List<string>>>(); 

This is how you specify the return type for a Task

Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.