windows运行时-WinRT C#中的多线程
本文关键字:多线程 运行时 -WinRT windows | 更新日期: 2023-09-27 18:00:11
我只想创建一个新线程,并在它上运行另一个DispatcherTimer实例。不希望它在GUI线程上运行,因为我不能让事件发生的频率超过每16毫秒一次(这是因为应用程序以60 FPS的速度运行)。使用ThreadPool是最好的方法吗?我对WinRT Windows应用商店应用程序中的线程处理一无所知,也找不到任何有趣的东西。谢谢你的帮助。
如果您计划只有一个线程,那么使用什么并不重要——无论它是Task、thread还是BackgroundWorker,都或多或少是一样的。
更重要的是:您只能在Dispatcher线程上使用DispatcherTimer,因此您需要查找其他内容。例如ThreadPoolTimer或用ResetEvent.Wait或Task.Delay自制的东西。然而,如果你想从这个线程更新UI,那么你需要调用Dispatcher.BeginInvoke,它的工作频率无论如何都不会超过每16ms一次。。。
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);
}