相关疑难解决方法(0)

在Parallel.ForEach中嵌套等待

在metro应用程序中,我需要执行许多WCF调用.有大量的调用,所以我需要在并行循环中进行调用.问题是并行循环在WCF调用完成之前退出.

你会如何重构这个按预期工作?

var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var customers = new  System.Collections.Concurrent.BlockingCollection<Customer>();

Parallel.ForEach(ids, async i =>
{
    ICustomerRepo repo = new CustomerRepo();
    var cust = await repo.GetCustomer(i);
    customers.Add(cust);
});

foreach ( var customer in customers )
{
    Console.WriteLine(customer.ID);
}

Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

c# wcf task-parallel-library async-await parallel.foreach

159
推荐指数
9
解决办法
10万
查看次数

并行操作批处理

在TPL(任务 - 并行 - 库)中是否有内置支持用于批处理操作?

我最近玩了一个例程,使用查找表即音译在字符数组上进行字符替换:

for (int i = 0; i < chars.Length; i++)
{
    char replaceChar;

    if (lookup.TryGetValue(chars[i], out replaceChar))
    {
        chars[i] = replaceChar;
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以看到这可能是平凡的并行化,所以跳进了第一次刺,我知道会因为任务太细粒度而表现更差:

Parallel.For(0, chars.Length, i =>
{
    char replaceChar;

    if (lookup.TryGetValue(chars[i], out replaceChar))
    {
        chars[i] = replaceChar;
    }
});
Run Code Online (Sandbox Code Playgroud)

然后我重新编写算法以使用批处理,这样就可以将工作分成不同细粒度的不同线程.这使得线程按预期使用,并且我得到了一些接近线性的加速.

我确信必须内置支持TPL中的批处理.什么是语法,我该如何使用它?

const int CharBatch = 100;
int charLen = chars.Length;

Parallel.For(0, ((charLen / CharBatch) + 1), i =>
{
    int batchUpper = ((i + 1) * CharBatch);

    for (int j = i * …
Run Code Online (Sandbox Code Playgroud)

c# parallel-processing task-parallel-library

8
推荐指数
1
解决办法
7714
查看次数