简体   繁体   中英

How to use HttpClient async methods with WebForm's RegisterAsyncTask in ASP.NET 4.0?

I am using HttpClient in ASP.NET framework 4.0. All example are I have seen using OnBeginXX/OnEndXXX or async/await(4.5) with RegisterAsyncTask. I need to ask how to make RegisterAsyncTask work with HtpClient's GetByteArrayAsync(or similar). Note this is ASP.NET 4.0?

Update: Just found that in 4.5 you have more overloads than 2.0 ,

Public method   PageAsyncTask(Func<Task>)   Initializes a new instance of the PageAsyncTask class using an event handler that enables the task to be handled.
Public method   PageAsyncTask(Func<CancellationToken, Task>)    Initializes a new instance of the PageAsyncTask class using an event handler that enables the task to be canceled.
Public method   PageAsyncTask(BeginEventHandler, EndEventHandler, EndEventHandler, Object)  Initializes a new instance of the PageAsyncTask class using the default value for executing in parallel.
Public method   PageAsyncTask(BeginEventHandler, EndEventHandler, EndEventHandler, Object, Boolean) Initializes a new instance of the PageAsyncTask class using the specified value for executing in parallel. 

Any other solution?

Update 2: I think TPL is not supported in 4.0 with recommended RegisterAsyncTask. Need to use HttpWebRequest with RegisterAssyncTask

You cannot use async / await on ASP.NET 4.0. This probably means you cannot use HttpClient either.

So, I recommend using WebClient or HttpWebRequest . These support older asynchronous patterns that ASP.NET 4.0 understands.

var client = new HttpClient();
client.GetByteArrayAsync("url").ContinueWith(t => {
    //insert your code here
});

it is work in .net 4.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM