- How to write a wrapper around an asynchronous method?
- public static void DownloadString(this Uri uri, Action<string> action)
- {
- if (uri == null) throw new ArgumentNullException("uri");
- if (action == null) throw new ArgumentNullException("action");
- var webclient = new WebClient();
- DownloadStringCompletedEventHandler handler = null;
- handler = (s, e) =>
- {
- var result = e.Result;
- webclient.DownloadStringCompleted -= handler;
- webclient.Dispose();
- action(result);
- };
- webclient.DownloadStringCompleted += handler;
- webclient.DownloadStringAsync(uri);
- }
- var uri = new Uri("http://someplace.com/books.json");
- uri.DownloadString(t =>
- {
- // Do something with the string
- });
- public void GetBooks(Uri uri, Action<List<Books>> action)
- {
- if (action == null) throw new ArgumentNullException("action");
- uri.DownloadString(t =>
- {
- var books = ParseJSON(t);
- action(books);
- });
- }
- this.GetBooks(new Uri("http://someplace.com/books.json"), books =>
- {
- // Do something with `List<Books> books`
- });
- void ParseJSON(string text, Action<List<Books>> action)
- var uri = new Uri("http://someplace.com/books.json");
- uri.DownloadString(t => ParseJSON(t, books =>
- {
- // Do something with `List<Books> books`
- // `string t` is also in scope here
- }));
- public static void DownloadString(
- this Uri uri,
- Action<string> action,
- Action<Exception> exception)
- {
- if (uri == null) throw new ArgumentNullException("uri");
- if (action == null) throw new ArgumentNullException("action");
- var webclient = (WebClient)null;
- Action<Action> catcher = body =>
- {
- try
- {
- body();
- }
- catch (Exception ex)
- {
- ex.Data["uri"] = uri;
- if (exception != null)
- {
- exception(ex);
- }
- }
- finally
- {
- if (webclient != null)
- {
- webclient.Dispose();
- }
- }
- };
- var handler = (DownloadStringCompletedEventHandler)null;
- handler = (s, e) =>
- {
- var result = (string)null;
- catcher(() =>
- {
- result = e.Result;
- webclient.DownloadStringCompleted -= handler;
- });
- action(result);
- };
- catcher(() =>
- {
- webclient = new WebClient();
- webclient.DownloadStringCompleted += handler;
- webclient.DownloadStringAsync(uri);
- });
- }
- public static void DownloadString(this Uri uri, Action<string> action)
- {
- uri.DownloadString(action, null);
- }
- var uri = new Uri("http://someplace.com/books.json");
- uri.DownloadString(t => ParseJSON(t, books =>
- {
- // Do something with `List<Books> books`
- }), ex =>
- {
- // Do something with `Exception ex`
- });
- ThreadPool.QueueUserWorkItem(DoWork);
- public void DoWork(){
- //Just remember that this code happens in a seperate thread so don't update
- //the UI. It will throw an exception. You would need to call
- //Form.BeginInvoke(UpdateFunction) in order to update the UI
- DoSomethingInteresting();
- }