c# - Error handling for Tasks inside Task.WhenAll -
i'm trying create web-scraper queries lot of urls in parallel , waits responses using task.whenall(). if 1 of tasks unsuccessful, whenall fails. expecting many of tasks return 404 , wish handle or ignore those. example:
string urls = enumerable.range(1, 1000).select(i => "https://somewebsite.com/" + i)); list<task<string>> tasks = new list<task<string>>(); foreach (string url in urls) { tasks.add(task.run(() => { try { return (new httpclient()).getstringasync(url); } catch (httprequestexception) { return task.fromresult<string>(""); } })); } var responsestrings = await task.whenall(tasks);
this never hits catch statement, , whenall fails @ first 404. how can whenall ignore exceptions , return tasks completed successfully? better yet, done somewhere in code below?
var tasks = enumerable.range(1, 1000).select(i => (new httpclient()).getstringasync("https://somewebsite.com/" + i)))); var responsestrings = await task.whenall(tasks);
thanks help.
you need use await
observe exception:
var tasks = enumerable.range(1, 1000).select(i => trygetstringasync("https://somewebsite.com/" + i)); var responsestrings = await task.whenall(tasks); var validresponses = responsestrings.where(x => x != null); private async task trygetstringasync(string url) { try { return await httpclient.getstringasync(url); } catch (httprequestexception) { return null; } }
Comments
Post a Comment