스택 오버플로에 대한 몇 가지 질문과 함께 이미이 주제를 다룬 몇 가지 블로그 게시물을 발견했지만 불행히도 그 중 누구도 내 필요를 충족시키지 못했습니다. 나는 내가하고 싶은 것을 보여주기 위해 몇 가지 샘플 코드부터 시작하겠습니다.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의 인스턴스로 설정해야한다고 생각합니다. 그렇지 않으면 반대편에서 이벤트를 처리하려는 새 디스패처가없는 새 스레드에 있습니다. –