How can I set a timeout for an Async function that doesn't accept a cancellation token?

前端 未结 3 1989
有刺的猬
有刺的猬 2021-01-04 20:13

I have my web requests handled by this code;

Response = await Client.SendAsync(Message, HttpCompletionOption.ResponseHeadersRead, CToken);

3条回答
  •  佛祖请我去吃肉
    2021-01-04 20:28

    Since returns a task, you can Wait for the Task which essentially is equivalent to specifying a timeout:

    // grab the task object
    var reader = response.Content.ReadAsStringAsync();
    
    // so you're telling the reader to finish in X milliseconds
    var timedOut = reader.Wait(X);  
    
    if (timedOut)
    {
        // handle timeouts
    }
    else
    {
        return reader.Result;
    }
    

提交回复
热议问题