c# - 你会如何简单地 Monitor.TryEnter

标签 c# .net vb.net parallel-processing

我正在努力让事情变得更简单。这是我的代码:

    If Threading.Monitor.TryEnter(syncRoot) Then
        Try
            'do something
        Finally
            Threading.Monitor.Exit(syncRoot)
        End Try
    Else
        'do something else
    End If

这在噪音方面甚至比 ReaderWriterLock 更糟糕。 我可以使用 C# 或 VB,因此欢迎回答适用于其中任何一个的问题。

最佳答案

使用委托(delegate)?

例如

public bool TryEnter(object lockObject, Action work) 
{
    if (Monitor.TryEnter(lockObject)) 
    {
       try 
       {
          work();
       }
       finally 
       {
           Monitor.Exit(lockObject);
       }        
       return true;
     }

     return false;
}

关于c# - 你会如何简单地 Monitor.TryEnter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/170051/

相关文章:

c# - System.NullReferenceException - 但调试器显示值不为空

c# - HttpWebRequest 到 HttpClient post 请求

c# - 使用 EF 将数据插入 SQL 数据库

c# - Autofac:IEnumerable<IInterface> 将始终返回从 IInterface 派生的对象列表?

c# - 使用 WebAdministration 管理单元从 .NET 运行 Powershell 脚本

.net - 什么时候应该更喜欢 ReBuild 而不是 Build?

c# - .NET Core - 无法加载文件或程序集

.net - 使用TCP或UDP套接字的VB 2008在线聊天应用程序

javascript - 在 Javascript 中验证日期时间

c# - 找不到 devexpress 网格设计器中的数据绑定(bind)属性