我发现了几个Stack Overflow问题以及一些已经涉及这个主题的博客帖子,但不幸的是他们中没有一个能够满足我的需求。我将从一些示例代码开始,展示我想要完成的任务。如何测试使用DispatcherTimer的类?
using System;
using System.Security.Permissions;
using System.Threading.Tasks;
using System.Windows.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MyApp
{
[TestClass]
public class MyTests
{
private int _value;
[TestMethod]
public async Task TimerTest()
{
_value = 0;
var timer = new DispatcherTimer {Interval = TimeSpan.FromMilliseconds(10)};
timer.Tick += IncrementValue;
timer.Start();
await Task.Delay(15);
DispatcherUtils.DoEvents();
Assert.AreNotEqual(0, _value);
}
private void IncrementValue(object sender, EventArgs e)
{
_value++;
}
}
internal class DispatcherUtils
{
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public static void DoEvents()
{
var frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
}
private static object ExitFrame(object frame)
{
((DispatcherFrame)frame).Continue = false;
return null;
}
}
}
此代码工作正常,如果,而不是使用DispatcherTimer,我使用普通的Timer。但是DispatcherTimer从不开火。我错过了什么?我需要什么来激发它?
我想你需要将SynchronizationContext设置为DispatcherSynchronizationContext的一个实例。否则,在等待的另一边,你正在一个新的线程,将有一个新的调度器,这不是你想要处理事件。 –