从多个线程进行调用时,如何锁定对dll的访问?

时间:2019-05-09 20:22:59

标签: c# asp.net .net dll

当我从请求轰炸创建的多个线程中调用非托管dll时,我的asp.net webapi应用程序失败。我无权访问该dll的源,并且该dll不是线程安全的。

当串行发出请求时,该应用程序运行良好,但是当并行发出多个请求时,该应用程序变得不稳定。

到目前为止,我的解决方案是尝试尝试一下,如果失败暂停一小段时间,请重试。这似乎可行,但是我相信使用互斥锁或Windows API或其他一些“我不知道”的解决方案应该有更好的方法。

我的代码示例:

public class CDFReader : IDisposable
{
    public CDFReader(string path)
    {
        // open cdf file using dll
    }

    // other cdf extraction methods exist that require the dll
}


public class SomeOtherClass
{
    // function call to CDFReader that gets called from
    // multiple request threads
    public Records GetRecords()
    {
        using (var cdf = CDFReader(somefilepath))
        {
            // extract data from cdf using CDFReader methods
        }
    }
}

当前,我通过将using块包装在fail-wait-retry中来解决我的问题,但希望从CDFReader中锁定。这样,使用CDFReader完成的所有操作都会自动处理,而不是锁定using块。

我愿意接受所有建议。

1 个答案:

答案 0 :(得分:0)

使用Named Mutex将DLL的使用锁定到此过程。唯一需要它的类是CDFReader,但是在完成使用CDFReader之前,必须确保将其丢弃,以免获得该锁并永远不会释放它。

public class CDFReader : IDisposable
{
    private Mutext _myMutex = new Mutex(false, "CDFDLLMutex");

    public CDFReader(string path)
    {
        _myMutex.WaitOne();   //This locks the DLL for the life of the CDFReader
        // open cdf file using dll
    }

    // other cdf extraction methods exist that require the dll

    //In your dispose method (because this class is IDisposable) call _myMutex.ReleaseMutex() and _myMutex.Dispose()
}


public class SomeOtherClass
{
    // function call to CDFReader that gets called from
    // multiple request threads
    public Records GetRecords()
    {
        //No modification needed to this method
        using (var cdf = CDFReader(somefilepath))
        {
            // extract data from cdf using CDFReader methods
        }
    }
}

以上显示了在CDFReader的整个生命周期中都使用互斥锁。既然您说它不是DLL的“线程安全”对象,所以我不确定是否要在CDFReader的整个生命周期中都使用互斥锁,或者您是否可以仅锁定单个方法调用。 / p>

如果您想锁定单个方法调用,只需调用(包括在构造函数中):

public void CDFMethod()
{
    _myMutex.WaitOne();    //With optional timeout
    //Do your processing in the method
    _myMutex.ReleaseMutex();
}

但是在处置.Dispose时,请务必确保互斥量为CDFReader