gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:05:05 24 4
gpt4 key购买 nike

出于测试目的,我需要在接口(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com