使用.FromAsync任务状态= WaitingForActivation

时间:2013-07-01 16:00:13

标签: c# asynchronous scheduled-tasks task-parallel-library task

我正在尝试发送url请求并异步获取响应,但是当我使用带有.ContinueWith方法的.fromAsync方法时,任务状态永远不会从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;
 }

1 个答案:

答案 0 :(得分:0)

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

  

beginMethod委托是在运行FromAsync的线程上启动的。此方法抛出beginMethod抛出的任何异常。

你通常会在没有lambdas的情况下写这个:

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

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