3

問題をシミュレートした次の C# コード スニペットがあります。このプログラムには、ReadRooms メソッドを呼び出す Service 関数があります。現在、別のスレッドでサービス メソッドを呼び出しています。ServiceCall と ReadRooms の両方のメソッドが同じように起動することを期待していましたが、正しくない結果を下回っています。

ここに画像の説明を入力

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        public static void ReadRooms(int i)
        {
            Console.WriteLine("Reading Room::" + i);
            Thread.Sleep(2000);
        }
        public static void CallService(int i)
        {
            Console.WriteLine("ServiceCall::" + i);
            ReadRooms(i);

        }
        static void Main(string[] args)
        {
            Thread[] ts = new Thread[4];
            for (int i = 0; i < 4; i++)
            {
                ts[i] = new Thread(() =>
                    {
                        int temp = i;
                        CallService(temp);


                    });
                ts[i].Start();
            }
            for (int i = 0; i < 4; i++)
            {
                ts[i].Join();
            }
            Console.WriteLine("done");
            Console.Read();

        }
    }
}
4

3 に答える 3

3

この行を入れる必要があります

int temp = i;

スレッド作成前

for (int i = 0; i < 4; i++)
{
    int temp = i;
    ts[i] = new Thread(() => CallService(temp));
    ts[i].Start();
}

このようにして、ラムダ式で使用される i のローカル コピーを作成します。

于 2013-08-23T18:39:39.827 に答える