有人可以向我解释如何返回任务的结果吗?
我目前正在尝试执行以下操作,但我的任务没有返回我期望的列表?这里有什么问题?
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
当你定义Task
作为泛型类型List
在你的情况下。就像是:
var taskLists = new List<Task<List<string>>>();
这是指定返回类型的方法Task
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)