gpt4 book ai didi

c# - C#Timer不会耗尽以形成卡住

转载 作者:太空宇宙 更新时间:2023-11-03 18:11:03 24 4
gpt4 key购买 nike

因此,当我尝试按下“按钮2”时,我希望会发生两件事。 b)在做某事的同时,我希望它计算某事花费的时间。但是,由于“做某事”会使程序感到饥饿,因此Form1冻结,并且它不会运行计时器。我是C#的菜鸟,所以我不知道如何在后台运行它。那么有什么开箱即用的想法吗?谢谢。

     int time = 0;
private void button2_Click(object sender, EventArgs e)
{
timer1.Start();
nowthen now = new nowthen();
now.dosomething(withthis); //This task is program hungry and causes the form to freeze
timer1.Stop();
time = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
time = time + 1;
label2.Text = time.ToString();
label2.Refresh();
}

最佳答案

对于.NET 4,请使用:

Task.Factory.StartNew((Action) delegate()
{
// this code is now executing on a new thread.
nowthen now = new nowthen();
now.dosomething(withthis);

// to update the UI from here, you must use Invoke to make the call on UI thread
textBox1.Invoke((Action) delegate()
{
textBox1.Text = "This update occurs on the UI thread";
});
});

关于c# - C#Timer不会耗尽以形成卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15437656/

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