如何定期更新Label控件的值?

时间:2012-04-01 12:57:14

标签: c# winforms delay

我正在尝试让标签显示一些文字,然后片刻之后刷新一下,以后能够重新显示其他内容。但是目前我不知道如何暂停标签(如果可能的话)。

到目前为止我的代码:

foreach (var x in mod)
{
      labelWARNING.Visible = true;
      labelWarningMessage.Text = "This module has a prerequisite module: " + x;
      //need a pause here to give user sufficient time to read the above text
      //labelWarningMessage.Text = "";
}

4 个答案:

答案 0 :(得分:1)

从您的问题来看,您似乎需要更改状态标签之类的值,以定期向用户显示信息。如果您使用的是winforms,则可以使用计时器和代表:

从您的问题来看,您似乎需要更改状态标签之类的值,以定期向用户显示信息。如果您使用的是winforms,则可以使用计时器和代表:

//First create a delegate to update the label value
public delegate void labelChanger(string s);

//create timer object
Timer t = new Timer();

//create a generic List to store messages. You could also use a Queue instead.
List<string> mod = new List<string>();

//index for list
int cIndex = 0;

//add this in your Form Load event or after InitializeComponent()
t.Tick += (timer_tick);
t.Interval = 5000;//how long you want it to stay.
t.Start();

//the timer_tick method
private void timer_tick(object s, EventArgs e)
{
     labelWarningMessage.Invoke(new labelChanger(labelWork), mod[cIndex]);
     cIndex++;
}

//the method to do the actual message display
private void labelWork(string s)
{
     labelWARNING.Visible = true;
     labelWarningMessage.Text = "This module has a prerequisite module: " + s;
}

我希望有所帮助。祝你好运。

编辑: 以为我很久以前发布这段代码只是为了回来发现我没有...但也许有人会发现它很有用。

此外,在这种情况下,此方法将是多余的,因为单独创建Timer将在不使用委托的情况下工作,并且仅对委托使用和UI线程访问部分有用。

答案 1 :(得分:0)

我会用另一个线程:

labelWARNING.Visible = true;
labelWarningMessage.Text = "This module has a prerequisite module: " + item;
new Thread(() => {
    Thread.Sleep(5000);
    Dispatcher.BeginInvoke((Action)(() => { labelWARNING.Visible = false; }));
}).Start();

(这适用于WPF,对于WinForms应该基本相同)

答案 2 :(得分:0)

我用了一个计时器。

private void timer1_Tick(object sender, EventArgs e)
{        
      labelWarningMessage.Text = "";
      labelWARNING.Visible = false;
}

答案 3 :(得分:0)

已更新为async / await。这将

// Update all text with warning message
foreach (var x in mod)
{
      labelWARNING.Visible = true;
      labelWarningMessage.Text = "This module has a prerequisite module: " + x;
}

// Wait 1 second or 1000ms    
await Task.Delay(1000);

// Now dismiss the message
foreach (var x in mod)
      labelWarningMessage.Text = "";

周围的功能必须是public async Task SomeMethod()
public async void buttonClick(object sender, RoutedEventArgs e)
使用await关键字

相关问题