【问题标题】:Textbox not displaying text and UI screen not moving文本框不显示文本和 UI 屏幕不移动
【发布时间】:2019-05-06 06:28:47
【问题描述】:

这是我的要求,我必须在计时器内使用while循环,点击按钮后启动应用程序UI被锁定无法移动,文本也无法在文本框中显示

下面是代码

using System;
using System.Windows.Forms;
namespace WinScreenLocked
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int Number = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            while (true)
            {
                textBox1.Text = Number.ToString();
                Number++;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            timer1.Start();
        }
    }
}

【问题讨论】:

  • 您的问题是什么?您将 UI 锁定在 UI 的线程(主线程)中。您需要创建一个不同的线程来处理控件的更改。如果您更改不同线程中的控件,则需要调用该操作(如果需要调用)。如果您不想锁定 UI,这是一个示例。 docs.microsoft.com/en-us/dotnet/framework/winforms/controls/…
  • 看起来帖子中的代码满足要求 - 有一个无限循环会冻结按计时器启动的 UI(假设您已正确配置计时器)......要求有点奇怪(它是很少听到让 UI 无响应的请求)...但是由于代码符合要求,因此不清楚您到底有什么问题?
  • 这是一个创建发布的示例项目,在实际项目中,计时器滴答事件中有while循环,while循环将循环直到它从一个api获取值,所以在那个时期只有UI被锁定跨度>

标签: c# winforms


【解决方案1】:
// Create a 30 min timer 
timer = new System.Timers.Timer(1800000);

// Hook up the Elapsed event for the timer.
timer.Elapsed += OnTimedEvent;

timer.Enabled = true;


private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
    // do stuff
}

通常需要注意的是:计时器不会非常准确,可能需要 GC.KeepAlive(timer)

另请参阅:Why does a System.Timers.Timer survive GC but not System.Threading.Timer?

【讨论】:

  • 已订阅,抱歉忘记在这里添加
  • 那可能是因为您需要一个异步计时器,请检查此答案。 stackoverflow.com/questions/15879476/…如果你必须依赖一个 API,你的程序将被冻结,直到它收到来自 API 的响应
【解决方案2】:

您可以停止线程以阻止用户界面,即使用

    System.Threading.Thread.Sleep(2000);

在2000毫秒以上等于2秒。

【讨论】:

    【解决方案3】:

    鉴于这是 winforms,您可以使用 Application.DoEvents() 来处理 UI 刷新。

    看到这个:https://social.msdn.microsoft.com/Forums/en-US/b1b1969d-8a51-496c-9274-a0ac1708a8b4/what-does-applicationdoevents-actually-do?forum=csharplanguage

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-18
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      相关资源
      最近更新 更多