如何获取任务的结果或返回值
本文关键字:结果 返回值 任务 何获取 获取 | 更新日期: 2023-09-27 18:33:56
有人可以向我解释如何返回任务的结果吗?我目前正在尝试执行以下操作,但我的任务没有返回我期望的列表?这里有什么问题?
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
}
要从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
定义为List
的泛型类型时,在Task
中指定返回类型。像这样:
var taskLists = new List<Task<List<string>>>();
这是您指定Task
返回类型的方式