gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:24 25 4
gpt4 key购买 nike

我有一个在任务中执行压缩解压缩的方法。现在我想要取消操作的能力。但是当我调用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com