【发布时间】:2013-11-13 17:29:28
【问题描述】:
我知道这是一个常见问题,但我似乎无法正确回答。我有一个发送到 gmail 并处理一些电子邮件的表格。我想在表单上有一个计时器来计算操作已经运行了多长时间。因此,一旦用户单击“开始导入”按钮,我希望计时器启动,一旦出现“完成”消息框,它应该停止。这是我目前所拥有的
现在,计时器只是停留在默认文本“00”;
namespace Import
{
public partial class Form1 : Form
{
Timer timer;
public Form1()
{
InitializeComponent();
}
private void btn_Import_Click(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = (1000);
timer.Enabled = true;
timer.Start();
timer.Tick += new EventHandler(timer_Tick);
// code to import emails
MessageBox.Show("The import was finished");
private void timer_Tick(object sender, EventArgs e)
{
if (sender == timer)
{
lblTimer.Text = GetTime();
}
}
public string GetTime()
{
string TimeInString = "";
int min = DateTime.Now.Minute;
int sec = DateTime.Now.Second;
TimeInString = ":" + ((min < 10) ? "0" + min.ToString() : min.ToString());
TimeInString += ":" + ((sec < 10) ? "0" + sec.ToString() : sec.ToString());
return TimeInString;
}
}
}
}
【问题讨论】:
-
你应该使用一些
Stopwatch而不是Timer来测量时间。 -
我在完整代码中有一个秒表,当 MessageBox 显示时,我将它打印出
stopwatch.Elapsed时间。但我也想对表格进行计数。 -
GetTime可以简化为return DateTime.Now.ToString("mm:ss"); -
gmail 处理是否在 UI 线程中运行,或者您是否启动了
BackgroundWorker(或类似的东西)?如果它在 UI 线程上运行,则计时器无法更新,因为 UI 线程正忙于处理。 -
是的@JimMischel ...这是我的问题:/我已经尝试纠正这个问题一天左右了。但我从未使用过多个线程。你能指点我一个好的教程吗?