我一直试图用我的头去思考锁,但我似乎无法弄清楚。下面的代码使用了锁,但仍然给出“集合已修改”错误。我缺少什么?
class Program
{
static List<int> lEntries = new List<int>();
static readonly object entriesLock = new object();
public static List<int> Entries {
get { lock (entriesLock) { return lEntries; } }
set { lock (entriesLock) { lEntries = value; } }
}
static void Main(string[] args)
{
// Run 20 times to reproduce the issue more often
for (int i = 0; i < 20; i++)
{
Task.Run(() =>
{
for (int j = 0; j < 10000; j++)
{ …Run Code Online (Sandbox Code Playgroud)