AlexSavAlexandrov
AlexSavAlexandrov

Reputation: 873

C# WinForms: activating a timer from a thread

public void timer_thing()
{
    Thread timer = new Thread(new ThreadStart(() =>
      {
          Thread.Sleep(500);
          if (is_mouse_down)
              timer1.Enabled = true;
      }
    ));
    timer.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    //some stuff happens here
}

As you can see I want the thread to activate the timer. But the timer doesn't activate. I guess this is not the right way. Or i'm missing something.

Upvotes: 1

Views: 414

Answers (6)

Nikos Baxevanis
Nikos Baxevanis

Reputation: 11201

You have to pass the timer1_Tick callback when you declare your timer object.

Upvotes: 0

GEverding
GEverding

Reputation: 3201

If you have questions about c# multithreading you should read this article. It is really helpful and will show you AutoresetEvent, ManualResetEvents, Thread Timers, Timers, etc. Really good general article.

Upvotes: 0

Yurii Hohan
Yurii Hohan

Reputation: 4171

This problem as described in literature has two solutions:

1) Active waiting

2) Notifications

If you want the active waiting solution(which is really an outdated one, your thread should have while loop).

If you want the notification when you should call some method which starts the timer in the mouse down event handler

Upvotes: 0

Brian Gideon
Brian Gideon

Reputation: 48949

It could be that is_mouse_down is false whenever the thread hits that instruction. The thread is not going to magically wait for it to turn true.

However, you have another, bigger problem to worry about. The thing is you cannot touch any UI element from a worker thread or any other other than the UI thread. This includes the System.Windows.Forms.Timer. All sorts of undefined chaos may ensue. Your application may fail unpredictably and spectacularly.

It is not really clear to me why a thread is needed in the first place. Can you not handle the Control.MouseDown event and enable the timer in the event handler for that event? That is how I would solve the problem.

Upvotes: 1

sll
sll

Reputation: 62504

You can use AutoResetEvent to automatically trigger it from Button Click handler.

So in thread just set:

autoResetEvent.WaitOne();
timer1.Enabled = true; 

and in button click handler:

autoResetEvent.Set();

BTW, why you can not initialize a Timer in the Click handler?

Upvotes: 0

thekip
thekip

Reputation: 3768

Your thread isn't waiting for the is_mouse_down event. It just checks after half a second and if it's not the time won't get enabled and the tread closes. Maybe you should try using an event?

Upvotes: 1

Related Questions