- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 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/
我刚开始使用企业库的 v5,似乎遇到了一些奇怪的问题。 像往常一样,我从日志记录开始。我刚刚添加了所需的引用并执行以下代码: Logger.Write("test"); 到目前为止没有什么特别的。检查
我有一个名为HandleMessage 的方法,启动了一个新线程来处理消息。如果成功获取锁对象,则进行处理。否则将消息放入队列。 SynchronizationLockException 总是在 Mo
这段代码有什么问题? 我总是得到一个 Object synchronization method was called from an unsynchronized block of code 异常(
我有以下代码,它基于 Monitor class example on the msdn website . private void WebRefresh_Click(object send
我正在尝试使用 SpinLock,但即使是单线程控制台应用程序中的这个最基本的代码,当我调用SpinLock.Exit() 时也会引发以下异常 System.Threading.Synchroniza
释放锁时我收到 SynchronizationLockException。 当然,我做的第一件事就是用谷歌搜索这个问题。我发现了两个主要的错误模式: 在与创建互斥锁不同的线程上释放互斥锁。 使用值类型
Unity 依赖项注入(inject)容器有一个似乎广为人知的问题,即 SynchronizedLifetimeManager 经常会导致 Monitor.Exit 方法抛出 Synchronizat
我正在使用 Monitor 类来管理关键部分。但有时我会遇到带有以下消息的 SynchronizationLockException An unhandled exception of type 'S
是否可以检测是否是同一个线程试图释放锁?我们在代码中有很多地方看起来像: try { try { if(!Monitor.TryEnter(obj, 2000))
我试图在 blazor(客户端)启动期间调用 api 以将语言翻译加载到 ILocalizer 中。 在这一点上,我尝试从 get 请求中获取 .Result blazor 在标题中引发错误。 这可以
我正在创建一段代码,从我们拥有的遗留系统中获取网页。为了避免过度查询,我缓存了获取到的URL。我正在使用 Monitor.Enter、Monitor.Exit 并仔细检查以避免发出两次请求,但是当使用
我是一名优秀的程序员,十分优秀!