在ReactiveCommand上调用.Execute()
会挂起或在下面的示例中创建死锁。为什么会发生这种情况,避免它的最佳方法是什么?
只有在调用Dispatcher.CurrentDispatcher时才会出现此错误。遗憾的是,没有称之为明显的答案,不是大项目的选择。
我在项目中有nuget包的reactiveui-core和reactiveui-winforms,都是v7.4.0。我正在使用Resharper从Visual Studio运行nunit测试。
代码是一个NUnit测试夹具,注意TimeoutAfterAsync是一个帮助方法,在一定的超时后取消测试,没有这个包装器就会观察到这种行为
[TestFixture]
public class ReactiveCommandTests
{
private static async Task<bool> ExecuteCommand()
{
await Task.Delay(1000);
return true;
}
public static ReactiveCommand<Unit, bool> Command = ReactiveCommand.CreateFromTask(ExecuteCommand);
public static ReactiveCommand<Unit, bool> CommandOnTaskpoolScheduler = ReactiveCommand.CreateFromTask(ExecuteCommand, outputScheduler: RxApp.TaskpoolScheduler);
public static ReactiveCommand<Unit, bool> CommandAfterDispatcherInvoked = ReactiveCommand.CreateFromTask(ExecuteCommand);
[Test, Order(1)]
public async Task Test()
{
//THIS WORKS
try
{
await TimeoutAfterAsync(
Command.Execute(),
TimeSpan.FromSeconds(5),
"control");
}
catch (TimeoutException)
{
Assert.Fail("Control case timed out (not expected)");
}
}
[Test, Order(2)]
public async Task Test_CreateCommandAfterDispatcherCall()
{
//This line causes unwanted behaviour
var x = Dispatcher.CurrentDispatcher;
//THIS FAILS
try
{
await TimeoutAfterAsync(
CommandAfterDispatcherInvoked.Execute(),
TimeSpan.FromSeconds(5),
"after dispatcher creation");
}
catch (TimeoutException)
{
Assert.Fail("Executing commandAfterDispatcherInvoked timed out (expected, but not understood");
}
}
[Test, Order(3)]
public async Task Test_CreateCommandWithThreadpoolScheduler()
{
//This line causes unwanted behaviour
var x = Dispatcher.CurrentDispatcher;
//THIS WORKS AGAIN (using ThreadpoolScheduler when creating ReactiveCommand)
try
{
await TimeoutAfterAsync(
CommandOnTaskpoolScheduler.Execute(),
TimeSpan.FromSeconds(5),
"after dispatcher creation, with thread pool");
}
catch (TimeoutException)
{
Assert.Fail("ThreadpoolScheduler case timed out (not expected)");
}
}
private static async Task<TResult> TimeoutAfterAsync<TResult>(IObservable<TResult> observable,
TimeSpan timeout,
string context)
{
var task = observable .ToTask();
var result = await Task.WhenAny(task, Task.Delay(timeout));
if (result == task)
{
// Task completed within timeout.
return task.GetAwaiter().GetResult();
}
else
{
// Task timed out.
throw new TimeoutException(context);
}
}
}
Dispatcher.CurrentDispatcher
很有趣;它为当前线程创建一个调度程序,如果它还没有!这会导致单元测试出现问题,因为新的调度程序是为线程池线程创建的,该线程不是STA,也没有消息泵。
理想的解决方案是不要打电话给CurrentDispatcher
。永远。使用await
或IProgress<T>
或(如果必须)SynchronizationContext
将结果/进度/事件传达给UI线程。这些抽象更容易为其创建测试环境。
但就目前而言,您可以使用WpfContext,这是Async CTP早期版本中包含的旧实用程序类型。 WpfContext.Run
将接受一个委托,为当前线程创建一个调度程序上下文,并在该调度程序上下文中执行委托,将其消息泵送到异步操作完成。