2013-04-25 32 views
2
namespace knowledge 
{ 
    public partial class FrmFtpr : Form 
    { 

    private readonly ILog _log = LogManager.GetLogger("Ftp"); 
     private CancellationTokenSource _cancellationTokenSource; 

    private IEnumerable<FtpHost> GetFtpHost() 
     { 
      //get all ftp site info 

      return ftpHost; 
     } 

     private async Task DoWork() 
     { 
      while (!_cancellationTokenSource.IsCancellationRequested) 
      { 
       var ftpHosts = GetFtpHosts(); 
       var ftpTasks = ftpHosts.Select(Upload); 
       await Task.WhenAll(ftpTasks); 
      } 
     } 

     private async Task Upload(FtpHost ftpHost) 
     { 
      //upload files to a ftp 
     } 


     private async void btnStart_Click(object sender, EventArgs e) 
     { 
      _cancellationTokenSource = new CancellationTokenSource(); 

      _log.Info(" Started"); 
      btnCancel.Enabled = true; 
      btnStart.Enabled = false; 
      await DoWork(); 
     } 

     private async void btnCancel_Click_1(object sender, EventArgs e) 
     { 
      _cancellationTokenSource.Cancel(); 
      _log.Info(" Stoped"); 
      btnStart.Enabled = true; 
      btnCancel.Enabled = false; 
     } 
    } 

} 

上面的代碼用於監視某些目錄,並將這些目錄中的文件上傳到不同的ftps。異步按鈕事件有時不起作用

如果GetFtpHost返回null或0,表單將凍結,但如果GetFtpHost返回某個值,則可以在開始和取消按鈕之間切換。 winform不會凍結。

+2

我的猜測是'GetFtpHosts'是什麼阻擋,這是該一種方法你沒有顯示出實現,所以對我們來說真的沒有太多的工作要做,我沒有看到你到目前爲止顯示的代碼有任何問題。 – Servy 2013-04-25 18:47:19

回答

0

通過修改下面的代碼,問題已解決。現在這個應用程序可以掃描迪爾斯週期(每1分鐘爲例),然後如果當前上傳不完整的,等候,否則開始新一輪的。

public partial class FrmFtpr : Form 
{ 
    private readonly ILog _log = LogManager.GetLogger("Ftp"); 
    private CancellationTokenSource _cancellationTokenSource; 
    private Task _task; 

    private IEnumerable<FtpHost> GetFtpHost() 
    { 
     //get all ftp site info 

     return ftpHost; 
    } 


    private async Task Upload(FtpHost ftpHost) 
    { 
     //upload files to a ftp 
    } 

    private void timer1_Tick(object sender, EventArgs e) 
    { 
     if (_task != null && !_task.IsCompleted) 
      return; 

     var ftpTargets = GetFtpTargets().ToList(); 

     if (ftpTargets.Count == 0) 
      return; 

     _task = Task.Factory.StartNew(() => 
      { 
       var tasks = ftpTargets.Select(Upload).ToArray(); 
       Task.WaitAll(tasks); 
      }); 
    } 


    private async void btnStart_Click(object sender, EventArgs e) 
    { 
     _cancellationTokenSource = new CancellationTokenSource(); 
     _log.Info(" Started"); 
     btnCancel.Enabled = true; 
     btnStart.Enabled = false; 
     timer1.Start(); 
    } 

    private async void btnCancel_Click_1(object sender, EventArgs e) 
    { 
     _cancellationTokenSource.Cancel(); 
     _task.Wait(); 
     _log.Info(" Stoped"); 
     timer1.Stop(); 
     btnStart.Enabled = true; 
     btnCancel.Enabled = false; 
    } 
}