【问题标题】:Threading Parallel Invoke, Action线程并行调用、操作
【发布时间】:2011-06-30 10:30:15
【问题描述】:
我的代码如下
public void DownloadConcurrent(Action<string> Methord)
{
Action<string>[] methordList = new Action<string>[Concurent_Downloads];
for (int i = 0; i < Concurent_Downloads; i++)
{
methordList[i] = Methord;
}
Parallel.Invoke(methordList);
}
Parallel.Invoke 报错:
"cannot convert from 'System.Action<string>[]' to 'System.Action[]'"
它调用的方法是
public void DownloadLinks(string Term)
{
}
【问题讨论】:
标签:
c#
.net
windows
multithreading
parallel-processing
【解决方案1】:
检查 Parallel.ForEach,如下所示
static void Main(string[] args)
{
List<string> p = new List<string>() { "Test", "Test2", "Test3"};
Parallel.ForEach(p, Test);
}
public static void Test(string test)
{
Debug.WriteLine(test);
}
这应该对你有用
HTH
多米尼克
【解决方案2】:
在你的情况下,如果你使用它会更容易
Parallel.ForEach
在你的字符串列表上而不是使用
并行调用
带有附加参数。如果您想坚持使用 Parallel.Invoke,请告诉我。
【解决方案3】:
Parallel.Invoke 接受 Action 数组,而您的代码将其传递给 Action<string> 数组。你可以做的是:
public void DownloadConcurrent(Action<string> Methord)
{
Action<string>[] methordList = new Action<string>[Concurent_Downloads];
var r = methordList.Select(a => (Action)(() => a("some_str"))).ToArray();
Parallel.Invoke(r);
}
您需要将 some_str 替换为每个操作的正确值