c# - How do I check if WebClient download is completed before I execute a function? -


i trying json files different urls. how make sure both files downloaded before try execute else.

my code looks this:

webclient url1 = new webclient(); url1.downloadstringcompleted += new downloadstringcompletedeventhandler(url1_downloadstringcompleted); url1.downloadstringasync(new uri("http://example.com")); webclient url2 = new webclient(); url2.downloadstringcompleted += new downloadstringcompletedeventhandler(url2_downloadstringcompleted); url2.downloadstringasync(new uri("http://anotherexample.com"));  dosomethingwithjson();  void url1_downloadstringcompleted(object sender, downloadstringcompletedeventargs e) {     if (e.error != null)          return;     json1 = jobject.parse(e.result); }  void url2_downloadstringcompleted(object sender, downloadstringcompletedeventargs e) {     if (e.error != null)          return;     json2 = jobject.parse(e.result); } 

right now, happens json1 , json2 returns null values whenever try display them in messagebox inside dosomethingwithjson(), , assuming might because haven't been downloaded completely.

the downloadstringasync() method returning before string downloaded because it's asynchronous method. if move dosomethingwithjson() method completed handlers called once request completed. may want add logic dosomethingwithjson() method it's work if variables needs populated (if indeed need them populated before start doing else).

webclient url1 = new webclient(); url1.downloadstringcompleted += new downloadstringcompletedeventhandler(url1_downloadstringcompleted); url1.downloadstringasync(new uri("http://example.com")); webclient url2 = new webclient(); url2.downloadstringcompleted += new downloadstringcompletedeventhandler(url2_downloadstringcompleted); url2.downloadstringasync(new uri("http://anotherexample.com")); var json1done = false; var json2done = false;   void url1_downloadstringcompleted(object sender, downloadstringcompletedeventargs e) {     if (e.error != null)          return;     json1 = jobject.parse(e.result);     json1done = true;     if(json1done && json2done)     {         dosomethingwithjson();     } }  void url2_downloadstringcompleted(object sender, downloadstringcompletedeventargs e) {     if (e.error != null)          return;     json2 = jobject.parse(e.result);     json2done = true;     if(json1done && json2done)     {         dosomethingwithjson();     } } 

alternatively, if using .net 4.5 use new async/await features:

webclient url1 = new webclient(); var json1task = url1.downloadstringtaskasync(new uri("http://example.com")); webclient url2 = new webclient(); var json2task = url2.downloadstringtaskasync(new uri("http://anotherexample.com"));  json1 = await json1task; json2 = await json2task;  dosomethingwithjson(); 

Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -