- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
出于测试目的,我需要在接口(interface)上模拟 Task
返回方法,以交回从不运行延续的任务。这是我到目前为止的代码:
// FooTests.cs
[Test]
public void Foo()
{
var yielder = Substitute.For<IYielder>();
yielder.YieldAsync().Returns(ThreadingUtilities.NeverReturningTask);
...
}
// ThreadingUtilities.cs
using System.Diagnostics;
using System.Threading.Tasks;
namespace Repository.Editor.Android.UnitTests.TestInternal.Threading
{
internal static class ThreadingUtilities
{
public static Task NeverReturningTask { get; } = CreateNeverReturningTask();
private async static Task CreateNeverReturningTask()
{
await new StopAwaitable();
Debug.Fail("Execution shouldn't reach here.");
}
}
}
// StopAwaitable.cs
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Repository.Editor.Android.UnitTests.TestInternal.Threading
{
internal struct StopAwaitable : INotifyCompletion
{
public bool IsCompleted => false;
public StopAwaitable GetAwaiter() => this;
public void GetResult()
{
Debug.Fail("The continuation shouldn't have been posted!");
}
public void OnCompleted(Action continuation)
{
// Ignore the continuation.
}
}
}
在这里,我创建了一个自定义等待类型,它只是忽略传递给它的延续——await new StopAwaitable()
与 return
具有本质上相同的效果从同步方法。然后,我在 async Task
方法中等待它,创建一个永远不会运行延续的 Task
对象。
我的问题是,这是最简洁/最清晰的方法吗?有没有其他方法可以创建这样一个不涉及自定义等待的任务,这会让不熟悉 async
工作原理的人感到困惑?
最佳答案
您可以使用:
var taskThatNeverReturns = Task.Delay(Timeout.Infinite);
docs指出参数表示:
The number of milliseconds to wait before completing the returned task, or -1 to wait indefinitely.
Timeout.Infinite
是一个值为 -1
的常量字段。
关于c# - 创建永不返回的任务的最简洁方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45954034/
我正在用 C# 编写动态语言的解释器,并将原始函数实现为具有虚拟 Apply 方法的抽象类 Primitive,其中每个实际原始函数都是重写 Apply 的子类。 (另一种方法是只拥有类 Primit
我正在用 C# 编写动态语言的解释器,并将原始函数实现为具有虚拟 Apply 方法的抽象类 Primitive,其中每个实际原始函数都是重写 Apply 的子类。 (另一种方法是只拥有类 Primit
我是 Dapper 的新手我正在尝试了解它实际上是如何映射事物的。我有以下数据库结构: calendar | Id | Name | meeting_room | Id | Calendar_id
抱歉问题标题很糟糕。有没有办法在一行中做到这一点: Button button = (Button)Gridview.Cells[0].FindControl("controlname"); butt
在 Java 中在声明点和使用点声明列表/数组文字的tersest方法是什么? 作为次要问题,我更喜欢一种不会导致编译时警告或要求抑制警告的方法。 注意:就我个人而言,这是针对Java 8ish on
什么是现代、简洁、快速的方法来测试节点是否有任何与给定选择器匹配的子节点? “简洁”是指类似于 jQuery 或函数式风格,例如避免循环。我知道本地选择器越来越多地使用这种类型的东西,但没有跟上发展的
getFirstNotNullResult 执行函数列表,直到其中一个函数返回非空值。 如何更优雅/简洁地实现 getNotNullFirstResult? object A { def main
根据 stackoverflow 上某人的推荐,我使用了 jquery succint https://github.com/micjamking/Succinct截断我在 php 网站上的帖子。 它
我是一名优秀的程序员,十分优秀!