线程并行调用,操作

本文关键字:操作 调用 并行 线程 | 更新日期: 2023-09-27 18:00:50

我的代码如下

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

并行。Invoke给出错误:

"cannot convert from 'System.Action<string>[]' to 'System.Action[]'"

它调用的方法是

public void DownloadLinks(string Term)
{ 
}

线程并行调用,操作

检查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);
    }

这应该为你做的技巧

HTHDominik

在您的情况下,如果使用会更容易

每个的并行

通过字符串列表而不是使用

并行调用

带有附加参数。如果您想继续使用Parallel.Invoke.

,请告诉我

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替换为每个操作的正确值