C#从System.Threading.Timer创建表单滴答失败

Erl*_* D. 2 c# multithreading winforms

使用System.Threading.Timer并在计时器的tick事件上初始化Windows窗体时,表单无响应.为什么会这样,我该如何避免呢?

这个简单的示例代码显示了问题; 两个第一个窗口("原始"和"手动")工作正常,但"定时器"立即变得无法响应.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsApplication1.Forms
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.Text = "Original";
            this.Left = 0;

            Form f = new Form();
            f.Text = "Manual";
            f.Show();
            f.Left = this.Width;

            TimerCallback tCallback = new TimerCallback(Timer_Tick);
            System.Threading.Timer timer = new System.Threading.Timer(tCallback, null, 1000, System.Threading.Timeout.Infinite);
        }

        void Timer_Tick(object o)
        {
            Form f = new Form();
            f.Text = "Timer";
            f.Show();
            f.Left = this.Width * 2;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

您正在使用a System.Threading.Timer,它将在线程池线程上执行 - 即没有与之关联的事件循环的线程.

如果你使用System.Windows.Forms.Timer,它将在UI线程上执行,一切都会好的.或者,使用a System.Timers.Timer并将其设置SynchronizingObject为父表单.