san*_*ngh 3 c# static multithreading
我有以下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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
你仍在"捕获循环变量".你正在创建一个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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17784 次 |
| 最近记录: |