使用标签描述表单的状态
本文关键字:状态 表单 描述 标签 | 更新日期: 2023-09-27 18:34:53
我遇到一种情况,我只需要一个标签,当用户单击按钮时,该标签可以在"就绪"和"进行中"之间切换。标签最初处于"就绪"状态。当用户单击按钮时,标签应显示为"正在进行",然后需要执行一些任务,例如复制文件等。成功完成任务后,标签应再次显示为"就绪"。现在我正在使用这段代码,标签状态没有改变。我怎样才能做到这一点。请帮忙。
private void button1_Click(object sender, EventArgs e)
{
status.Text = "In Progress";
if (listBox1.Items.Count == 0)
{
MessageBox.Show("Please select a file to upload");
}
FtpClient client = new FtpClient("*******", "*******", "******");
string fileName = getFileNameFromPath(listBox1.Items[0].ToString());
string localFile = listBox1.Items[0].ToString();
string remoteFile = "**********/"+fileName;
string link = client.upload(remoteFile, localFile);
listBox1.Items.RemoveAt(0);
textBox1.Text = link;
status.Text = "Ready";
}
你在长时间运行的过程中阻止了 UI 线程,既阻止了 UI 更新文本值,要么接收用户输入,要么执行任何操作。
您需要异步执行长时间运行的工作,以免阻塞 UI 线程。
理想情况下,您将拥有FtpClient
提供的异步方法(甚至更好的是,它会返回一个Task
(。 这将允许你写这样的东西:
private async void button1_Click(object sender, EventArgs e)
{
status.Text = "In Progress";
if (listBox1.Items.Count == 0)
{
MessageBox.Show("Please select a file to upload");
}
FtpClient client = new FtpClient("*******", "*******", "******");
string fileName = getFileNameFromPath(listBox1.Items[0].ToString());
string localFile = listBox1.Items[0].ToString();
string remoteFile = "**********/" + fileName;
string link = await client.uploadAsync(remoteFile, localFile);
listBox1.Items.RemoveAt(0);
textBox1.Text = link;
status.Text = "Ready";
}
然后你就完成了。 如果它不提供任何异步方法,那么作为解决方法,您只需启动一个新任务即可在后台完成工作:
private async void button1_Click(object sender, EventArgs e)
{
status.Text = "In Progress";
if (listBox1.Items.Count == 0)
{
MessageBox.Show("Please select a file to upload");
}
FtpClient client = new FtpClient("*******", "*******", "******");
string fileName = getFileNameFromPath(listBox1.Items[0].ToString());
string localFile = listBox1.Items[0].ToString();
string remoteFile = "**********/" + fileName;
string link = await Task.Run(() => client.upload(remoteFile, localFile));
listBox1.Items.RemoveAt(0);
textBox1.Text = link;
status.Text = "Ready";
}
如果您没有 C# 5.0 和 .NET 4.5 可以使用await
则可以使用BackgroundWorker
:
private void button1_Click(object sender, EventArgs e)
{
status.Text = "In Progress";
if (listBox1.Items.Count == 0)
{
MessageBox.Show("Please select a file to upload");
}
string fileName = getFileNameFromPath(listBox1.Items[0].ToString());
string localFile = listBox1.Items[0].ToString();
string remoteFile = "**********/" + fileName;
var worker = new BackgroundWorker();
worker.DoWork += (s, args) =>
{
FtpClient client = new FtpClient("*******", "*******", "******");
args.Result = client.upload(remoteFile, localFile);
};
worker.RunWorkerCompleted += (s, args) =>
{
listBox1.Items.RemoveAt(0);
textBox1.Text = args.Result as string;
status.Text = "Ready";
};
worker.RunWorkerAsync();
}