Async按钮事件有时不工作

本文关键字:工作 按钮 事件 Async | 更新日期: 2023-09-27 18:10:59

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返回一些值,我可以在开始和取消按钮之间切换。天气不会冻结。

Async按钮事件有时不工作

通过修改下面的代码,问题已经解决。现在这个应用程序可以扫描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;
    }
}