如何获取任务的结果或返回值?

时间:2014-12-11 17:24:38

标签: c# task-parallel-library

有人可以向我解释如何返回任务的结果吗? 我目前正在尝试执行以下操作,但我的任务不会返回我期望的列表吗?这有什么问题?

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

}

1 个答案:

答案 0 :(得分:9)

要从Task返回结果,您需要定义TaskTask<TResult>并将结果的返回类型作为通用参数传递。 (否则任务将不返回任何内容)

例如:

        // 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;
        });

问题是您没有指定任务将返回任何内容

您已经定义了一个不返回任何内容的任务列表。

当您将Task定义为Task的通用类型时,您需要做的是在List中指定返回类型。类似的东西:

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

这是指定Task

的返回类型的方法