C # Creating a form from System.Threading.Timer file

When using System.Threading.Timer and initializing the window form in a timer event, the form becomes inactive. Why is this, and how can I avoid it?

This simple code example shows the problem; the first two windows ("Original" and "Manual") work fine, but "Timer" immediately stops responding.

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;
        }
    }
}

      

+2


source to share


1 answer


You are using System.Threading.Timer

that will run on a thread pool thread, that is, one that does not have an event loop associated with it.



If you use System.Windows.Forms.Timer

it will execute on the UI thread and you should be fine. Alternatively use System.Timers.Timer

and set SynchronizingObject

to parent form.

+7


source







All Articles