c# - DotNetZip 取消任务中的提取

标签 c# task dotnetzip

我有一个在任务中执行压缩解压缩的方法。现在我想要取消操作的能力。但是当我调用 Cancel() 方法时,一切似乎都立即停止并且 while 永远运行:

public class OsiSourceZip
{
    private const string ZipPassword = "******";

    private bool _extractionDone;
    private bool _cancelExtraction;

    public async Task Extract(string sourceFile, string extractionDir)
    {
        Task extraction = Task.Run(() =>
        {
            using (ZipFile zipf = ZipFile.Read(sourceFile))
            {
                zipf.ExtractProgress += delegate(object sender, ExtractProgressEventArgs args)
                {
                    args.Cancel = _cancelExtraction;
                    RaiseExtractionProgressUpdate(args);
                };
                zipf.Password = ZipPassword;
                zipf.Encryption = EncryptionAlgorithm.WinZipAes256;
                zipf.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
                zipf.ExtractAll(extractionDir);
            }
        });

        await extraction;
        _extractionDone = true;
        RaiseSourceInstallationCompleted();
    }

    public void Cancel()
    {
        _cancelExtraction = true;
        while (!_extractionDone)
        {
            Thread.Sleep(500);
        }
    }
}

我在 args.Cancel = _cancelExtraction; 上设置了一个断点,但是一旦调用 Cancel() 方法,事件就不再触发。

最佳答案

我已经找到了解决办法。我基本上摆脱了我自己的 Cancel 方法,并按照 dotnetzip 框架的要求进行操作。在进度事件中。

假设您想在 Form 关闭时取消操作。我捕获 FormClosing 事件,取消关闭过程并记住关闭请求。下次进度事件触发时,我在事件参数中设置了 cancel 属性,并在 completed 事件中自己关闭了 Form:

public partial class MainForm : Form
{
    private bool _closeRequested;

    private void OnSourceInstallationCompleted(object sender, EventArgs e)
    {
        if (_closeRequested) { this.Close(); }            
    }

    private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (!_closeRequested)
        {
            _closeRequested = true;
            e.Cancel = true;
        }
    }

    private void OnExtractionProgressUpdate(object sender, ExtractProgressEventArgs e)
    {
        e.Cancel = _closeRequested;
    }
}

我认为它相当丑陋,但它有效......

关于c# - DotNetZip 取消任务中的提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43322996/

相关文章:

c# - itextsharp pdf 工作中的 gridview 列宽需要样式

C# 为可变数量的参数构建参数列表的简单方法

c# - 如何递归压缩文件夹?

c# - 任务取消最佳实践

c# - 如何使用太长/重复的路径处理解压缩 ZipFile

c# - DotNetZip 从 MemoryStream 打开 zip 文件

c# - PayPal API 混淆 - ExpressCheckout 使用哪一个

c# - 在查询开始和结束时调用 'where' 函数在性能上有区别吗?

c# - 如何使用 async/await 查找 'hangs' 的哪个方法?

c# - 什么相当于 python 中的 C# 任务