2017-04-10 117 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; 
    } 
} 

我認爲這是相當醜陋,但它的工作原理....