【问题标题】:C# equivalent of Python's ThreadPoolC# 相当于 Python 的 ThreadPool
【发布时间】:2020-09-28 15:21:24
【问题描述】:

我想问一下 Python 的 Threadpool 函数是否有任何替代方法。 我是 C# 新手。我有一个将字符串作为输入的函数,并且我有一个输入列表。我想要的是在多个线程(最多 12 个)中执行该函数,以便向每个线程传递来自列表的一个字符串输入,如果列表的大小大于线程数,则它等待任何一个线程完成其执行,然后在线程中使用下一个输入再次启动函数。希望这个问题对大家有意义。

我已经在 Python 中完成了这个:

def myfunc(input):
 print(input)

if__name__ == "__main__":
 inputs = [1,12,2,3,4,5,6,7,8,9,1,0,1,2,3,4,5,6,4,8,97,7]
 ThreadPool(12).map(myfunc, inputs)

【问题讨论】:

  • .NET 中有一个ThreadPool 类,只有静态成员(不可创建)。阅读其SetMinThreads 方法的文档特别有趣。

标签: python c# multithreading threadpool


【解决方案1】:
static void Main()
{
    var inputs = new[] { 1, 12, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 2, 3, 4, 5, 6, 4, 8, 97, 7 };
    Parallel.ForEach(inputs, new ParallelOptions { MaxDegreeOfParallelism = 12 }, MyFunc);
}
static void MyFunc(int value) { /*...*/ }

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 2010-12-21
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多