Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //this will work
- private void button1_Click(object sender, RoutedEventArgs e)
- {
- var query = ctx.AccountSet;
- query.BeginExecute((result) =>
- {
- textBox1.Text = query.EndExecute(result).First().Name;
- }, null);
- }
- //this will fail
- private void button2_Click(object sender, RoutedEventArgs e)
- {
- System.Threading.Tasks.Task.Factory.StartNew(RestAsync);
- }
- void RestAsync()
- {
- var query = ctx.AccountSet;
- var async = query.BeginExecute(null, null);
- var task = System.Threading.Tasks.Task.Factory.FromAsync<Account>(async, (result) =>
- {
- return query.EndExecute(result).First(); // <- Exception thrown here
- });
- textBox1.Dispatcher.BeginInvoke(() =>
- {
- textBox1.Text = task.Result.Name;
- });
- }
- private static AsyncCallback SyncContextCallback(AsyncCallback callback)
- {
- SynchronizationContext sc = SynchronizationContext.Current;
- // If there is no SC, just return what was passed in
- if (sc == null) return callback;
- // Return a delegate that, when invoked, posts to the captured SC a method that
- // calls the original AsyncCallback passing it the IAsyncResult argument
- return asyncResult => sc.Post(result => callback((IAsyncResult)result), asyncResult);
- }
- protected override void OnMouseClick(MouseEventArgs e) {
- // The GUI thread initiates the asynchronous Web request
- Text = "Web request initiated";
- var webRequest = WebRequest.Create("http://Wintellect.com/");
- webRequest.BeginGetResponse(SyncContextCallback(ProcessWebResponse), webRequest);
- base.OnMouseClick(e);
- }
- private void ProcessWebResponse(IAsyncResult result) {
- // If we get here, this must be the GUI thread, it's OK to update the UI
- var webRequest = (WebRequest)result.AsyncState;
- using (var webResponse = webRequest.EndGetResponse(result)) {
- Text = "Content length: " + webResponse.ContentLength;
- }
- }
- public override void UpdateCanvas(object parameter)
- {
- Action<GraphPane> startToUpdate = StartToUpdate;
- GraphPane selectedPane = Canvas.HostingPane.PaneList.Find(p => p.Title.Text.Equals(defaultPanTitle));
- startToUpdate.BeginInvoke(selectedPane, FormSyncContext.SyncContextCallback(RefreshCanvas), selectedPane);
- }
- public static AsyncCallback SyncContextCallback(AsyncCallback callback)
- {
- // Capture the calling thread's SynchronizationContext-derived object
- SynchronizationContext sc = SynchronizationContext.Current;
- // If there is no SC, just return what was passed in
- if (sc == null) return callback;
- // Return a delegate that, when invoked, posts to the captured SC a method that
- // calls the original AsyncCallback passing it the IAsyncResult argument
- return asyncResult => sc.Post(result => callback((IAsyncResult)result), asyncResult);
- }
Add Comment
Please, Sign In to add comment