2017-04-10 75 views
3

我有一个方法在任务中执行压缩提取。现在我想要取消操作的功能。但是,当我打电话Cancel()方法似乎一切都立即停止和while一直运行:DotNetZip取消提取任务

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()方法被调用了解雇。

回答

0

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

假设您想在Form关闭时取消操作。我捕获了FormClosing事件,取消关闭程序并记住关闭请求。接下来的时间进度事件触发,我设置事件参数的的cancel财产和关闭Form自己在completed事件:

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; 
    } 
} 

我认为这是相当丑陋,但它的工作原理....