Question

I would like to simply create a new thread and run another instance of DispatcherTimer on it. Don't want it to run on the GUI thread because I can't get the event happen more often than once per 16 ms (it's because the app runs at 60 FPS). Is using ThreadPool the best way to do that? I don't really know anything about threading in WinRT Windows Store apps, and I couldn't find anything interesting. Thanks for help.

Était-ce utile?

La solution

If you plan to have only one thread, then it doesn't really matter what you use - it's all more or less the same, no matter if it's called Task, Thread or BackgroundWorker.

Much more important: You can use the DispatcherTimer only on a Dispatcher thread, so you need to find something else. E.g. the ThreadPoolTimer or something homebrown with ResetEvent.Wait or Task.Delay. However if you want to update the UI from this thread, then you need to call Dispatcher.BeginInvoke which won't work more often that once per 16ms anyway ...

void TestDispatcherTimer()
{
    // need to create and start DispatcherTimer on UI thread, because ...
    DispatcherTimer dt = new DispatcherTimer();
    dt.Interval = TimeSpan.FromMilliseconds(5);
    dt.Tick += dt_Tick;
    dt.Start();

    Task.Run(() =>
    {
        // ... if uncommented, each single line crashes because of wrong thread
        // DispatcherTimer dt = new DispatcherTimer(); 
        // dt.Interval = TimeSpan.FromMilliseconds(5); 
        // dt.Tick += dt_Tick; 
        // dt.Start(); 
    });
}

void dt_Tick(object sender, object e)
{
    DateTime now = DateTime.Now;
    int id = Environment.CurrentManagedThreadId; // id will always be the UI thread's id
    System.Diagnostics.Debug.WriteLine("tick on thread " + id + ": " + now.Minute + ":" + now.Second + "." + now.Millisecond);
}

void TestThreadpoolTimer()
{
    // it doesn't matter if the ThreadPoolTimer is created on UI thread or any other thread
    ThreadPoolTimer tpt = ThreadPoolTimer.CreatePeriodicTimer(tpt_Tick, TimeSpan.FromMilliseconds(5));
}

void tpt_Tick(ThreadPoolTimer timer)
{
    DateTime now = DateTime.Now;
    int id = Environment.CurrentManagedThreadId; // id will change, but never be the UI thread's id
    System.Diagnostics.Debug.WriteLine("tick on thread " + id + ": " + now.Minute + ":" + now.Second + "." + now.Millisecond);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top