System.Windows.Forms.Timer can only run on the UI thread

1. Non-UI thread execution startup timer is invalid

private void Form1_Load(object sender, EventArgs e)
        {
            // 允许跨线程访问控件
            Control.CheckForIllegalCrossThreadCalls = false;

            Task.Run(() =>
            {
                usbListen();
            });
        }

private void usbListen()
        {
            checkUSBTimer = new Timer();
            checkUSBTimer.Interval = 5 * 1000;
            checkUSBTimer.Enabled = true;
            checkUSBTimer.Tick += new EventHandler(startCheckUSB);
            checkUSBTimer.Start();

        }
public void startCheckUSB(object sender, EventArgs e)
        {

            WriteToTextBox("日志打印");
        }

2. Go to the UI thread to start the timer valid

Modify the usbListen() function code

private void usbListen()
        {
            BeginInvoke(new MethodInvoker(delegate
            {
                checkUSBTimer = new Timer();
                checkUSBTimer.Interval = 5 * 1000;
                checkUSBTimer.Enabled = true;
                checkUSBTimer.Tick += new EventHandler(startCheckUSB);
                checkUSBTimer.Start();
            }));

        }

Guess you like

Origin blog.csdn.net/qq1326702940/article/details/130842067