簡體   English   中英

在.net 4.0中使用task.continuewith模擬異步/等待

[英]Simulate async/await with task.continuewith in .net 4.0

是否可以在不使用Microsoft.Bcl.Async包的情況下模擬.NET 4.0中async / await的行為?

我嘗試跑步

Task myTask = Task.Factory.Startnew(MyMethod,...)
myTask.ContinueWith((x)=>{
    //do stuff when myTask is completed
},...);
//code that i hoped would run without waiting for myTask

但這會在myTask運行時阻止我的UI。 在搜索此問題時,我發現了這個問題 ,似乎提出了完全相同的問題,甚至提出了帶有完整代碼示例的解決方案。 但是,當我嘗試調用GetResponseWithRetryAsync (或使用task.Start()運行它,或將其包裝在Task.Factory.StartNew() )時,它仍然阻塞了我的UI線程。 為什么所有這些運行任務的方式都會阻止UI?

編輯 :示例代碼按用戶1的要求阻止我的UI

Task myTask = Task.Factory.StartNew(MyMethod, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
myTask.ContinueWith((x) =>
    { 
     this.Title="Done!";
    }, new CancellationToken(), TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());

MyMethod在哪里

    public void MyMethod(){
        WebRequest request = WebRequest.Create("http://google.com/");
        request.Credentials = CredentialCache.DefaultCredentials;
        WebResponse response = request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(dataStream);

        string responseFromServer = reader.ReadToEnd();
        Console.WriteLine(responseFromServer);
        reader.Close();
        response.Close();
    }

無需編譯器和框架的幫助就可以模仿async-await ,盡管很難正確解決。 您需要注意捕獲上下文,異常處理,返回結果等。

您提到的情況不應在整個異步操作中阻塞UI。 但是,在異步操作(例如DNS解析)之前,可能需要完成一些同步工作。 如果是這種情況,請使用Task.Run並將其工作卸載到ThreadPool線程以提高響應速度。

Task myTask = Task.Factory.Startnew(MyMethod)
myTask.ContinueWith((x)=>
{
    //do stuff when myTask is completed
},new CancellationToken(),TaskContinuationOptions.OnlyOnRanToCompletion,TaskScheduler.FromCurrentSynchronizationContext());

這意味着繼續操作不會阻塞您的UI線程。 這里最主要的是TaskScheduler.FromCurrentSynchronisationContext()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM