code_junkie

Implementing a nested asynch “call stack” scenario in .NET

Nov 14th, 2011
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. static void AsyncHelp<T>(Func<T> f, Action<Exception> econt, Action<T> cont) {
  2. var t = new Thread((_) => {
  3. try {
  4. var res = f();
  5. System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => cont(res));
  6. } catch (Exception ex) {
  7. System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => econt(ex));
  8. }
  9. });
  10. t.Start();
  11. }
  12.  
  13. some_handler() {
  14. var id = mytextbox.Text; // Save from UI to local
  15. AsyncHelp(
  16. () => GetBla(id),
  17. bla => result.Text = bla.ToString(), // This is safe cause it's dispatched
  18. ex => error.Text = ex.ToString()
  19. );
  20. }
  21.  
  22. Exception ex;
  23. Result r;
  24. var mre = new ManualResetEvent(false);
  25. myService.OnGetBlaCompleted += (_, e) => {
  26. ex = e.Error;
  27. r = e.Result;
  28. mre.Set();
  29. }
  30. myService.GetBlaAsync(id);
  31. mre.WaitOne();
  32. if (ex != null) throw ex;
  33. // and so on
Add Comment
Please, Sign In to add comment