多个线程在C#中调用相同的方法 [英] Multiple threads calling same method in C#

查看:1207
本文介绍了多个线程在C#中调用相同的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下C#代码段,在其中模拟了我的问题.在此程序中,我有一个Service函数,该函数调用ReadRooms方法. 现在,我在不同的线程上调用服务方法.我原以为ServiceCall和ReadRooms方法都将同样触发,但是我得到的结果不正确.

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.

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

        }
    }
}

推荐答案

您仍在捕获循环变量".您正在创建temp,但是已经太晚了,因为已经捕获了i.

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

尝试一下:

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

这篇关于多个线程在C#中调用相同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆