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

}

以上代码用于监控一些目录,并将这些目录中的文件上传到不同的ftp。

如果 GetFtpHost 返回 null 或 0,表单将冻结,但如果 GetFtpHost 返回一些值,我可以在开始和取消按钮之间切换。winform不会冻结。

4

1 回答 1

0

通过修改如下代码,问题已得到解决。现在这个应用程序可以扫描dirs周期(例如每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;
    }
}
于 2013-05-06T22:11:02.893 回答