7

Here is my code..

public DispatcherTimer tmr = new DispatcherTimer();

void somefunction (parameters){

if (something)
  tmr.Start();
if (something else)
  tmr.Stop();

   }

My problem is that I can't access the Start/Stop methods of the tmr object from the second function since it runs on a different thread!!!

Can somebody please help me?? I am struck wih this problem for almost 3 days! :(

AnthonyWJones
  • 187,081
  • 35
  • 232
  • 306
Gowtham
  • 386
  • 5
  • 20

1 Answers1

2

You need to Invoke it via Dispatcher (for marshaling the call from another thread) like so

Deployment.Current.Dispatcher.BeginInvoke((Action)(()=>timer.Start())
Muhammad Hasan Khan
  • 34,648
  • 16
  • 88
  • 131
  • thanks hasan..but since "tmr" is already a DispatcherTimer object, it does not have a Dispatcher method in it! This would have worked if tmr is just a timer object, but it is not.. :( – Gowtham Oct 10 '11 at 07:30
  • it still does not work. The error I get is.. System.Windows.Threading.Dispatcher' does not contain a definition for 'Invoke' and no extension method 'Invoke' accepting a first argument of type 'System.Windows.Threading.Dispatcher' could be found (are you missing a using directive or an assembly reference?) – Gowtham Oct 10 '11 at 07:40
  • 1
    @Gowtham Try begininvoke instead – Muhammad Hasan Khan Oct 10 '11 at 07:41
  • I tried setting Isenabled to true or false. but that doesnt work either. Can you please tell me how to use BeginInvoke ?? I really appreciate the interest you are taking in this....:) – Gowtham Oct 10 '11 at 07:44
  • sorry...that was my bad. Thanks a lot !!! It worked!!!! Can you post your source..for further reference! – Gowtham Oct 10 '11 at 07:50
  • 2
    +1 However there is no need to cast a lambda of () to `Action` in fact since the timer.Start has the same signature as `Action` there isn't any need for a lambda at all. This will work: `Deployment.Current.Dispatcher.BeginInvoke(timer.Start);` – AnthonyWJones Oct 10 '11 at 12:28
  • @AnthonyWJones you're right. Didn't notice it was taking Action. In WPF it is just a Delegate I think (for which casting is required). – Muhammad Hasan Khan Oct 10 '11 at 12:37