c# – 如何为不接受取消令牌的异步函数设置超时?

我有这个代码处理的Web请求;
Response = await Client.SendAsync(Message,HttpCompletionOption.ResponseHeadersRead,CToken);

在读取响应头之后和内容完成读取之前返回.当我打电话给这一行来获取内容时……

return await Response.Content.ReadAsStringAsync();

我希望能在X秒后停止它.但它不接受取消令牌.

解决方法

虽然您可以依赖WithCancellation进行重用,但是更简单的超时解决方案(不会抛出OperationCanceledException)将是使用Task.Delay创建超时任务并等待使用Task.WhenAny完成第一个任务:
public static Task<TResult> WithTimeout<TResult>(this Task<TResult> task,TimeSpan timeout)
{
    var timeoutTask = Task.Delay(timeout).ContinueWith(_ => default(TResult),TaskContinuationOptions.ExecuteSynchronously);
    return Task.WhenAny(task,timeoutTask).Unwrap();
}

或者,如果您想要在超时而不是仅返回默认值(即null)的情况下抛出异常:

public static async Task<TResult> WithTimeout<TResult>(this Task<TResult> task,TimeSpan timeout)
{
    if (task == await Task.WhenAny(task,Task.Delay(timeout)))
    {
        return await task;
    }
    throw new TimeoutException();
}

用法是:

var content = await Response.Content.ReadAsStringAsync().WithTimeout(TimeSpan.FromSeconds(1));

相关文章

1:最直白的循环遍历方法,可以分为遍历key--value键值对以及...
private void ClearTextBox(){ foreach (var control in pnl...
原文叫看《墨攻》理解IOC概念 2006年多部贺岁大片以让人应接...
右击文件夹-&gt;安全选项卡-&gt;添加-&gt;高级-...