gpt4 book ai didi

c# - 异常: Object synchronization method was called from an unsynchronized block of code

转载 作者:太空宇宙 更新时间:2023-11-03 17:57:02 25 4
gpt4 key购买 nike

我有几个写入同一int的线程。每个线程递增
整数值。同步增量操作的简单方法是什么?
锁语句仅对对象有效,因此我无法使用它。我也尝试过
下列的:

static int number=0;

static void Main(string[] args)
{
ThreadStart ts = new ThreadStart(strtThread);
new Thread(ts).Start();
new Thread(ts).Start();
new Thread(ts).Start();
new Thread(ts).Start();
new Thread(ts).Start();
new Thread(ts).Start();
Console.ReadLine();
}

public static void strtThread()
{
bool lockTaken = false;

Monitor.Enter(number,ref lockTaken);
try
{
Random rd = new Random();
int ee = rd.Next(1000);
Console.WriteLine(ee);
Thread.Sleep(ee);
number++;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (lockTaken)
{
Monitor.Exit(number);
}

}
}

它给了我以下错误:

Object synchronization method was called from an unsynchronized block of code.

最佳答案

您可以使用Interlocked.Increment Method自动增加整数而不加锁定:

public static void strtThread()
{
Interlocked.Increment(ref number);
}

如果您有多个语句,则可以创建一个 object实例,也可以创建 lock:
private static int number = 0;
private static readonly object gate = new object();

public static void strtThread()
{
lock (gate)
{
number++;
}
}

关于c# - 异常: Object synchronization method was called from an unsynchronized block of code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8248045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com