gpt4 book ai didi

c# - 异步按钮事件有时不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 16:14:16 25 4
gpt4 key购买 nike

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 没有卡住。

最佳答案

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

关于c# - 异步按钮事件有时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16222342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com