Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

multithreading - Multiple threads calling same method in C#

I have the following C# code snippet in which I have simulated my problem. In this program I have a Service function that call ReadRooms method. Now I am calling the service method on different threads. I was expecting that both ServiceCall and ReadRooms method will fired equally but I am getting below result that is not correct.

enter image description here

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

        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are still 'capturing the loop variable'. You are creating a temp but too late, when i is already captured.

Try this:

for (int i = 0; i < 4; i++)
{
   int temp = i;              // outside the lambda
   ts[i] = new Thread(() =>
   {
        //int temp = i;       // not here
        CallService(temp);
   });
   ts[i].Start();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...