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

前端之家收集整理的这篇文章主要介绍了c# – 如何获取任务的结果或返回值?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以向我解释如何返回任务的结果吗?
我目前正在尝试执行以下操作,但我的任务不会返回我期望的列表吗?这里有什么问题?
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,dec....
   }

   //Do some work about results
}
static List<string> GetAdditionalInfo(string hash)
{
    //this code returns information about the hash in List of strings

}

解决方法

要从Task返回结果,您需要将Task定义为:Task< 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中的List的泛型类型时,您需要做的是在Task中指定返回类型.就像是:

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

这是您为任务指定返回类型的方式

原文链接:https://www.f2er.com/csharp/239078.html

猜你在找的C#相关文章