c# - Error with await operator -
there problem code. how can solve problem? problem in await operator.
public mymodel() { httpclient client = new httpclient(); httpresponsemessage response = await client.getasync("https://api.vkontakte.ru/method/video.get?uid=219171498&access_token=d61b93dfded2a37dfcfa63779efdb149653292636cac442e53dae9ba6a049a75637143e318cc79e826149"); string googlesearchtext = await response.content.readasstringasync(); jobject googlesearch = jobject.parse(googlesearchtext); ilist<jtoken> results = googlesearch["response"].children().skip(1).tolist(); ilist<mainpage1> searchresults = new list<mainpage1>(); foreach (jtoken result in results) { mainpage1 searchresult = jsonconvert.deserializeobject<mainpage1>(result.tostring()); searchresults.add(searchresult); }
you're trying use await
within constructor. can't - constructors always synchronous.
you can use await
within method or anonymous function async
modifier; can't apply modifier constructors.
one approach fixing create static async method create instance - relevant awaiting, , pass results simple synchronous constructor. callers need handle appropriately, of course.
public static async task<mymodel> createinstance() { string googlesearchtext; using (httpclient client = new httpclient()) { using (httpresponsemessage response = await client.getasync(...)) { googlesearchtext = await response.content.readasstringasync(); } } // synchronous constructor rest... return new mymodel(googlesearchtext); }
Comments
Post a Comment