c# - Debugger stops after async HttpClient.GetAsync() call in visual studio -
i'm trying test follwing http request method
public async task<httpcontent> get(string url) { using (httpclient client = new httpclient()) // breakpoint using (httpresponsemessage response = await client.getasync(url)) // can't reach below point using (httpcontent content = response.content) { return content; } } however, debugger seems skipping code below 2nd comment. i'm using visual studio 2015 rc, ideas? tried checking tasks window , saw nothing
edit: found solution
using system; using system.net.http; using system.threading.tasks; namespace consoletests { class program { static void main(string[] args) { program program = new program(); var content = program.get(@"http://www.google.com"); console.writeline("program finished"); } public async task<httpcontent> get(string url) { using (httpclient client = new httpclient()) using (httpresponsemessage response = await client.getasync(url).configureawait(false)) using (httpcontent content = response.content) { return content; } } } } turns out because c# console app ended after main thread ends guess, because after adding console.readline() , waiting bit, request did return. guessed c# wait until task execute , not end before it, suppose wrong. if elaborate on why happened nice.
when main exits, program exits. outstanding asynchronous operations canceled , results discarded.
so, need block main exiting, either blocking on asynchronous operation or other method (e.g., calling console.readkey block until user hits key):
static void main(string[] args) { program program = new program(); var content = program.get(@"http://www.google.com").wait(); console.writeline("program finished"); } one common approach define mainasync exception handling well:
static void main(string[] args) { mainasync().wait(); } static async task mainasync() { try { program program = new program(); var content = await program.get(@"http://www.google.com"); console.writeline("program finished"); } catch (exception ex) { console.writeline(ex); } } note blocking on asynchronous code considered bad idea; there few cases should done, , console application's main method happens 1 of them.
Comments
Post a Comment