gpt4 book ai didi

.net - SpinLock 抛出 SynchronizationLockException

转载 作者:行者123 更新时间:2023-12-02 07:38:02 25 4
gpt4 key购买 nike

我正在尝试使用 SpinLock,但即使是单线程控制台应用程序中的这个最基本的代码,当我调用SpinLock.Exit() 时也会引发以下异常

System.Threading.SynchronizationLockException was unhandled by user code
Message=The calling thread does not hold the lock. Source=mscorlib

这是完整的源代码...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication48
{
class Program
{
static readonly SpinLock SpinLock = new SpinLock();
static void Main(string[] args)
{
bool lockTaken = false;
try
{
SpinLock.Enter(ref lockTaken);
if (lockTaken)
Console.WriteLine("Lock taken");
}
finally
{
if (lockTaken)
SpinLock.Exit();
}
Console.WriteLine("Done");
}
}
}

最佳答案

SpinLock 是一个结构体,您正在从只读字段中读取它。 C# 规范表示,在这种情况下,为了调用可能会发生变化的函数,必须将结构复制到可变局部变量。这发生在幕后。

您对 Enter 和 Exit 的调用发生在您的锁的新副本上。因此,Enter 是在未锁定的锁上进行操作的。

不要将 SpinLock 变量设置为只读,因为它正在发生变化。

关于.net - SpinLock 抛出 SynchronizationLockException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11224130/

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