c# - 创建永不返回的任务的最简洁方法是什么?

标签 c# .net asynchronous async-await task

出于测试目的,我需要在接口(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# - 使用自定义模型通过 C# 中的 Forms Recognizer V3 nuget 从表中提取数据

c# - 更改字体样式

javascript - 动态生成的数据网格控件删除链接中不会调用经典 ASP.NET 删除事件

.net - 向 .net core csproj 文件添加依赖项

.net - 在 wcf 服务调用上设置 CultureInfo?

c# - 什么更快 : if statement or conditional operator? (C#)

c# - C# Delegate 中的奇怪死循环

algorithm - 如何积累异步数据?

C# 异步方法回调

javascript - console.log 的非 volatile 替代品