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

}

これを 1 つずつ実行する代わりに (私の計算では 415 日間ノンストップで永遠にかかります)、この for ループの各反復を非同期で呼び出す最も簡単な方法は何ですか?

ほとんどの質問と記事は非常に古いものです (2001 年頃!) 確かに、より現代的なアプローチが必要ですか?

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

4

4 に答える 4

2
于 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

私があなたを正しく理解していれば、これらを別のスレッドで実行したいと考えています。これを行う 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 はハイパースレッディングのため)、隠蔽される可能性があるクライアント (while(true) サイクルがクロークされていないことを本当に願っています) を待つ必要があるためです。少なくとも部分的に。

于 2012-07-18T18:10:05.163 に答える