androider
androider

Reputation: 992

Dispatcher timer tick function not called in anther thread

 public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Thread HeartRateThread = new Thread(startThread);
        HeartRateThread.Name = "Class1";
        HeartRateThread.Start();
    }

    private void startThread(object obj)
    {
        new Class1();
    }
}

 public class Class1
{
    public  Class1()
    {
        DispatcherTimer timer1 = new DispatcherTimer();
        timer1.Interval = new TimeSpan(0,0,0,1);
        timer1.Tick += timer1_tick;
        timer1.Start();
    }

    private void timer1_tick(object sender, EventArgs e)
    {
        Debug.WriteLine("timer called");
    }
}

I am trying to enable this timer_tick function fromanother thread as it is obvious in the code section of maInWindow. However, the Class1 constructor is called but timertick functin is not enabled. However if i do this on the main thread, everything works fine. Any reason for this.And how can I get it working?

Upvotes: 0

Views: 2611

Answers (4)

Suresh
Suresh

Reputation: 4149

DispatcherTimer can only work run on a UI thread. However, in your case you are creating a DispatcherTimer on a background thread. DispatcherTimer, internally tries to get Dispatcher.CurrentDispatcher, in your case it gets dispatcher for the background thread, not for the main UI thread.

Do you really need DispatcherTimer? If you are not going to manipulate any UI elements in the timer1_tick method, then you are better off to go with a different timer, like System.Timers.Timer.

Refer to this to read more about available Timers in .net.

Upvotes: 3

J R B
J R B

Reputation: 2136

you can use Dispatcher for call startThread method.

 object objParameter = "parametervalue";
        Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(
                                                                                () => startThread(objParameter))); 

Upvotes: 0

Clemens
Clemens

Reputation: 128061

Without having tested it, I guess you have to pass the MainWindow's Dispatcher to the DispatcherTimer on construction. Otherwise it will create its own:

private void startThread(object obj)
{
    new Class1(Dispatcher);
}

...

public Class1(Dispatcher dispatcher)
{
    DispatcherTimer timer1 =
        new DispatcherTimer(DispatcherPriority.Background, dispatcher);

    timer1.Interval = new TimeSpan(0,0,0,1);
    timer1.Tick += timer1_tick;
    timer1.Start();
}

Upvotes: 0

Daniel
Daniel

Reputation: 9521

Maybe you can try something like this:

private void timer1_tick(object sender, EventArgs e)
{
    Application.Current.Dispatcher.BeginInvoke(new Action(() => Debug.WriteLine("timer called")));
}

Upvotes: 0

Related Questions