gpt4 book ai didi

c# - 使用 .FromAsync 任务状态 = WaitingForActivation

转载 作者:太空宇宙 更新时间:2023-11-03 16:11:07 26 4
gpt4 key购买 nike

我正在尝试发送 url 请求并异步获取响应,但是当我将 .fromAsync 方法与 .ContinueWith 方法一起使用时,任务状态永远不会从 WaitingForActivation 更改为运行。我试过使用 task.Start() 但它不能与 ContinueWith 一起使用。我将如何在我的代码中将任务状态更改为正在运行?

public void pageCheck(){
IAsyncResult asyncResult;
Uri uri = new Uri(TempURL); //TempUrl is assigned a string beforehand
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
try{
Task<WebResponse> task = Task.Factory.FromAsync(
myReq.BeginGetResponse,
asyncResult => myReq.EndGetResponse(asyncResult),
(Object)null);

task.ContinueWith(t =>
{
var responseCode = (HttpWebResponse)t.Result;
ReadStreamFromResponse(t.Result);
if(responseCode.StatusCode == HttpStatusCode.OK){
//updatestatus
reponseCode.Close();
}
}
);
}
//catch exceptions
}

private String ReadStreamFromResponse(WebResponse response) {
StreamReader responseStream = new StreamReader(response.GetResponseStream());
string str = responseStream.ReadToEnd();
return str;
}

最佳答案

Task.Factory.FromAsync自动安排任务。来自 the documentation :

The beginMethod delegate is started on the thread that FromAsync is running on. This method throws any exceptions thrown by the beginMethod.

您通常会在没有 lambda 的情况下编写此代码:

Task<WebResponse> task = Task<WebResponse>.Factory.FromAsync(
myReq.BeginGetResponse,
myReq.EndGetResponse,
null);

如果您使用的是 .NET 4.5 和 C# 5,则可以使用 WebRequest.GetResponseAsync也直接。

关于c# - 使用 .FromAsync 任务状态 = WaitingForActivation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17408790/

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