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不会冻结。