gpt4 book ai didi

C# : Some questions about a method which allows to display a label for a specific time

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

我在谷歌中搜索了一种允许我在特定时间显示标签的方法,我发现了这个:

public void InfoLabel(string value)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(InfoLabel), new object[] { value });
return;
}
barStaticItem3.Caption = value;

if (!String.IsNullOrEmpty(value))
{
System.Timers.Timer timer = new System.Timers.Timer(6000) { Enabled = true };
timer.Elapsed += (sender, args) =>
{
this.InfoLabel(string.Empty);
timer.Dispose();
};
}

}

这个方法我实在是看不懂:

-为什么我们使用:InvokeRequired

-此方法的用途:this.Invoke()

-这是做什么用的:new Action<string>(InfoLabel)

-为什么我们使用那个标志:=>

最佳答案

所有与 invoke 相关的东西都是因为编写该代码的人使用了错误的 Timer (语言中有很多)。您应该在此处使用 System.Windows.Forms.Timer

public void InfoLabel(string value)
{
System.Windows.Forms.Timer timer = new Timer();

timer.Interval = 1000;//or whatever the time should be.
timer.Tick += (sender, args) =>
{
label1.Text = value;
timer.Stop();
};
timer.Start();
}

表单计时器将在它自己的实现中包含代码,这些代码执行类似于您示例中代码的操作(尽管我发现这样做的方式特别困惑)。它将确保 Tick 事件在 UI 线程中运行,这样您就不需要添加所有样板代码。

=> 是一个 lambda 表达式。这是一种定义新匿名方法的方法,该方法采用两个参数 senderargs

您也可以使用 Task 来解决这个问题,而不是使用计时器:

public void InfoLabel2(string value)
{
Task.Factory.StartNew(() => Thread.Sleep(1000)) //could use Task.Delay if you have 4.5
.ContinueWith(task => label1.Text = value
, CancellationToken.None
, TaskContinuationOptions.None
, TaskScheduler.FromCurrentSynchronizationContext());
}

关于C# : Some questions about a method which allows to display a label for a specific time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12749124/

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