c# - Avoid returning type Task<Object> from an async function when using HttpClient -
i making http calls using system.net.http.httpclient. seems calls must asynchronous.
let's have project structure of following: mvc web app -> business layer -> data layer
in data layer making http calls web api return data , end using function this:
public async task<ilist<product>> getproducts() { httpresponsemessage response = await client.getasync("api/products"); string data = await response.content.readasstringasync(); ilist<product> products = jsonconvert.deserializeobject<ilist<product>>(data); return products; } this goes through businesslayer:
public task<ilist<product>> getproducts(string name = null) { return _repository.getproducts(name); } then in mvc controller:
public iactionresult index() { task<ilist<product>> productstask = _manager.getproducts(); ilist<product> productsnontask = products.result.tolist(); return view(); } do have make every single function return list of type task<ilist<product>> leading mvc controller? can see in mvc controller have retrieve products task wrapped around them. debugger looks kind of strange when go view list of products through it. can see convert them regular list of product.
i wondering if correct thing have of functions return type task<ilist<product>> way mvc controller or if there workaround functions can still return standard list of product continue use async capabilities of httpclient?
update: there wrong doing following:
public ilist<product> getproducts() { task<httpresponsemessage> response = client.getasync("api/products"); if (response.result.issuccessstatuscode) { string data = response.result.content.readasstringasync().result; ilist<product> products = jsonconvert.deserializeobject<ilist<product>>(data); retval = products; } }
if want operation asynchronous needs asynchronous way up.
the minute block on task wait or result it's no longer asynchronous.
so, no. either use async way or don't use @ all.
i wonder... if there workaround functions can still return standard list of product continue use async capabilities of httpclient?
no, there isn't really.
you should make code asynchronous comes many benefits in scalability , performance. if you're against doing can use webclient has synchronous web operations.
Comments
Post a Comment