我發現了幾個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的一個實例。否則,在等待的另一邊,你正在一個新的線程,將有一個新的調度器,這不是你想要處理事件。 –