0

这是一个简单的 .NET 4 应用程序。这是我要运行的代码:

string username = "userfoo";
string password = "passwordfoo";

for (int i = 0; i < 2000; i++)
{    
    uint matchId;
    if (!uint.TryParse(i.ToString(), out matchId))
    {
        Console.WriteLine("Invalid Match ID!");
        return;
    }

    Client client = new Client (username, password, matchId);

    // connect
    client.Connect();

    client.Wait();

    if (client.Match != null)
    {
        Console.WriteLine("Inserting match: #{0}", client.Match.match_id);
        Helpers.MatchHelper.AddMatchToDatabase(client.Match);
    }
    else
    {
        Console.WriteLine("Couldn't get match: #{0}", 1);
    }

}

而是一个接一个地执行此操作(根据我的计算,这将永远需要 415 天不间断),异步调用此 for 循环的每次迭代的最简单方法是什么?

大多数问题和文章都很古老(大约在 2001 年!)肯定有更现代的方法吗?

http://msdn.microsoft.com/en-us/magazine/cc301332.aspx

4

4 回答 4

2

您可以在此处找到信息:http: //msdn.microsoft.com/en-us/library/ff963552.aspx。基本上,您只需使用Parallel.For(0, n, x => doSomething). 这需要处理并行化。这是 PLINQ 的一个功能,它非常易于使用,在我的经验中效果很好。

您的示例将如下所示:

string username = "userfoo";
string password = "passwordfoo";

Parallel.For(0, 2000, i =>
{    
    uint matchId;
    if (!uint.TryParse(i.ToString(), out matchId))
    {
        Console.WriteLine("Invalid Match ID!");
        return;
    }

    Client client = new Client (username, password, matchId);

    // connect
    client.Connect();

    client.Wait();

    if (client.Match != null)
    {
        Console.WriteLine("Inserting match: #{0}", client.Match.match_id);
        Helpers.MatchHelper.AddMatchToDatabase(client.Match);
    }
    else
    {
        Console.WriteLine("Couldn't get match: #{0}", 1);
    }
});
于 2012-07-18T17:53:00.157 回答
1

我认为这就是您要寻找的:http: //www.codeproject.com/Articles/71285/Introducing-NET-4-0-Parallel-Programming

于 2012-07-18T17:52:19.290 回答
1

你应该看看任务并行库

于 2012-07-18T17:52:21.110 回答
1

如果我理解正确,您想在单独的线程中运行这些。这是执行此操作的一种方法:您需要将代码从循环移动到 void 函数中:

void MyThreadInsteadOfLoop(object parameter)
{
int i  = (int)parameter;
uint matchId;
if (!uint.TryParse(i.ToString(), out matchId))
{
    Console.WriteLine("Invalid Match ID!");
    return;
}

Client client = new Client (username, password, matchId);

// connect
client.Connect();

client.Wait();

if (client.Match != null)
{
    Console.WriteLine("Inserting match: #{0}", client.Match.match_id);
    Helpers.MatchHelper.AddMatchToDatabase(client.Match);
}
else
{
    Console.WriteLine("Couldn't get match: #{0}", 1);
}
}

在您的主线程中,如果您愿意,您需要准备线程以运行、启动它们并等待它们完成。这是代码:

//Create threads
List<Thread> threads = new List<Thread>();
for(int i=0;i<2000;i++)
{
    threads.Add(new Thread(new ParameterizedThreadStart(MyThreadInsteadOfLoop)));
}
//Start threads
int x = 0;
foreach(var t in threads)
{
    t.Start(x);
    x++;
}
//wait for the threads to finish
foreach(var t in threads)
{
    t.Join();
}

请注意,您必须使 MatchHelper 类以及与您的线程交换数据的其他类线程安全,这往往会给您的程序增加大量开销。此外,您可能会遇到网络连接问题。一次只有 [NumberOfCpuCores]*2 个线程会主动工作(*2 因为超线程),但是由于您必须等待客户端(我真的希望这不是一段时间(真)循环隐藏),所以可能会被隐藏至少部分。

于 2012-07-18T18:10:05.163 回答