【发布时间】:2016-11-11 19:12:18
【问题描述】:
我想我在这里遗漏了一些基础知识并且无法解决问题..
以下程序的输出与预期不符。有人可以帮我理解这里的问题吗?
using System;
using System.Threading;
public class Program
{
private static readonly object _lock = new object();
public static void Main()
{
for (var i = 0; i < 10; i++)
{
//Console.WriteLine("Start "+i);
System.Threading.Thread thread = new System.Threading.Thread(() => ExecuteInBackground(i));
thread.IsBackground = true;
thread.Start();
}
}
private static void ExecuteInBackground(Object obj)
{
lock (_lock)
{
Console.WriteLine("A "+obj);
test.ttt(obj);
}
}
}
public static class test
{
public static void ttt(object obj)
{
Console.WriteLine("B "+ obj);
}
}
我希望在输出中看到 0 到 9.. 但实际输出如下..
A 1
B 1
A 1
B 1
A 3
B 3
A 4
B 4
A 5
B 5
A 6
B 6
A 7
B 7
A 8
B 8
A 9
B 9
A 10
B 10
非常感谢任何帮助。
请随意使用https://dotnetfiddle.net/nYfbMU中的代码
谢谢, 雷迪。
【问题讨论】:
标签: c# multithreading locking