c# - C#中多个线程调用同一个方法

标签 c# multithreading static

我有以下 C# 代码片段,我在其中模拟了我的问题。在这个程序中,我有一个调用 ReadRooms 方法的服务函数。 现在我在不同的线程上调用服务方法。我原以为 ServiceCall 和 ReadRooms 方法会同样触发,但我得到的结果低于不正确的结果。

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

        }
    }
}

最佳答案

您仍在“捕获循环变量”。您正在创建 temp 但为时已晚,此时 i 已被捕获。

试试这个:

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# - C#中多个线程调用同一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18409547/

相关文章:

python - 在 Heroku 上为 Django 处理静态文件和模板的正确方法

c# - Topshelf - 找不到类型或命名空间名称 Topshelf

Python:启动类方法时线程不起作用

ios - UItableViewCell 问题的高度

java - 我如何模拟提供使用 JMockit 模拟的类的实例的静态方法?

java - 尝试通过 python 脚本启动 Minecraft 服务器时出现内存问题

c# - MVC3 项目中的目录

c# - 在 WinForms UI (.NET3.5) 中淡出具有透明度的图像

c# - 如何检索枚举的整数值?

c++ - 如何在多线程环境中使用旧的单线程 C++ 库