为什么使用两个手动重置事件会导致此处出现死锁

本文关键字:事件 死锁 两个 为什么 | 更新日期: 2023-09-27 18:26:13

我正在使用Starksoft.Net.Ftp.为上传执行异步操作

看起来是这样的:

    public void UploadFile(string filePath, string packageVersion)
    {
        _uploadFtpClient= new FtpClient(Host, Port, FtpSecurityProtocol.None)
        {
            DataTransferMode = UsePassiveMode ? TransferMode.Passive : TransferMode.Active,
            FileTransferType = TransferType.Binary,
        };
        _uploadFtpClient.TransferProgress += TransferProgressChangedEventHandler;
        _uploadFtpClient.PutFileAsyncCompleted += UploadFinished;
        _uploadFtpClient.Open(Username, Password);
        _uploadFtpClient.ChangeDirectoryMultiPath(Directory);
        _uploadFtpClient.MakeDirectory(newDirectory);
        _uploadFtpClient.ChangeDirectory(newDirectory);
        _uploadFtpClient.PutFileAsync(filePath, FileAction.Create);
        _uploadResetEvent.WaitOne();
        _uploadFtpClient.Close();
    }
    private void UploadFinished(object sender, PutFileAsyncCompletedEventArgs e)
    {
        if (e.Error != null)
        {
            if (e.Error.InnerException != null)
                UploadException = e.Error.InnerException;
        }
        _uploadResetEvent.Set();
    }

如您所见,其中有一个ManualResetEvent,它被声明为类顶部的私有变量:

private ManualResetEvent _uploadResetEvent = new ManualResetEvent(false);

好吧,感觉只是它应该等待上传完成,但它必须是异步的,才能报告进度,仅此而已。

现在,这很好用。如果愿意的话,我还有第二种方法可以取消上传。

public void Cancel()
{
    _uploadFtpClient.CancelAsync();
}

当上传被取消时,服务器上的一个目录也必须被删除。我也有一个方法:

    public void DeleteDirectory(string directoryName)
    {
        _uploadResetEvent.Set(); // As the finished event of the upload is not called when cancelling, I need to set the ResetEvent manually here.
        if (!_hasAlreadyFixedStrings)
            FixProperties();
        var directoryEmptyingClient = new FtpClient(Host, Port, FtpSecurityProtocol.None)
        {
            DataTransferMode = UsePassiveMode ? TransferMode.Passive : TransferMode.Active,
            FileTransferType = TransferType.Binary
        };
        directoryEmptyingClient.Open(Username, Password);
        directoryEmptyingClient.ChangeDirectoryMultiPath(String.Format("/{0}/{1}", Directory, directoryName));
        directoryEmptyingClient.GetDirListAsyncCompleted += DirectoryListingFinished;
        directoryEmptyingClient.GetDirListAsync();
        _directoryFilesListingResetEvent.WaitOne(); // Deadlock appears here
        if (_directoryCollection != null)
        {
            foreach (FtpItem directoryItem in _directoryCollection)
            {
                directoryEmptyingClient.DeleteFile(directoryItem.Name);
            }
        }
        directoryEmptyingClient.Close();
        var directoryDeletingClient = new FtpClient(Host, Port, FtpSecurityProtocol.None)
        {
            DataTransferMode = UsePassiveMode ? TransferMode.Passive : TransferMode.Active,
            FileTransferType = TransferType.Binary
        };
        directoryDeletingClient.Open(Username, Password);
        directoryDeletingClient.ChangeDirectoryMultiPath(Directory);
        directoryDeletingClient.DeleteDirectory(directoryName);
        directoryDeletingClient.Close();
    }
    private void DirectoryListingFinished(object sender, GetDirListAsyncCompletedEventArgs e)
    {
        _directoryCollection = e.DirectoryListingResult;
        _directoryFilesListingResetEvent.Set();
    }

由于取消时没有调用上传的完成事件,我需要在DeleteDirectory方法中手动设置ResetEvent。

现在,我在这里做什么:我首先列出目录中的所有文件,以便删除它们,因为填充的文件夹无法删除。

此方法GetDirListAsync也是异步的,这意味着我需要另一个ManualResetEvent,因为我不希望表单冻结。

此ResetEvent是_directoryFilesListingResetEvent。它的声明类似于上面的_uploadResetEvent

现在,问题是,它转到_directoryFilesListingResetEvent的WaitOne调用,然后它就停滞了。出现死锁,表单冻结。(我也在代码中标记了它)

为什么?我试图移动_uploadResetEvent.Set()的调用,但它没有改变。有人看到问题了吗?

当我尝试在没有任何上传的情况下单独调用DeleteDirectory-方法时,它也能正常工作。我认为问题是两个ResetEvents使用相同的资源或其他东西,并且它们自己重叠,我不知道。

谢谢你的帮助。

为什么使用两个手动重置事件会导致此处出现死锁

您没有正确使用此库。您添加的MRE会导致死锁。这始于_uploadResetEvent.WaitOne(),阻塞了UI线程。这通常是非法的,CLR通过泵送消息循环本身来确保UI不会完全失效。这使得它看起来像是还活着,例如,它仍然会重新绘制。大致相当于DoEvents(),尽管没有那么危险。

但它最大的问题是,它不允许PutFileAsyncCompleted事件处理程序运行,底层异步工作者是一个普通的BackgroundWorker。它在启动它的同一个线程上启动它的事件,这非常好。但在UI线程空闲之前,它不能调用其RunWorkerCompleted事件处理程序。这并不好,线程被困在WaitOne()调用中。与您现在正在调试的情况完全相同,您的GetDirListAsyncCompleted事件处理程序由于同样的原因无法运行。因此,它只是冻结在那里,无法取得进展。

因此,完全消除_uploadResetEvent,转而使用UploadFinished()方法。您可以从e.Cancelled属性中了解它是否已取消。只有然后才能启动代码来删除目录。遵循相同的模式,使用相应的XxxAsyncCompleted事件来决定下一步要做什么。根本不需要MRE。

查看源代码,FtpClient使用BackgroundWorker执行异步操作。这意味着它的完成事件将被发布到创建工作者时设置的任何SynchronizationContext。我敢打赌,CancelAsync的完成会将您推回到UI线程上,当您在目录列表重置事件上调用WaitOne时,该线程会阻塞。GetDirListAsyncCompleted事件被发布到UI消息循环中,但由于UI线程被阻止,它将永远不会运行,也永远不会设置重置事件。

死锁。