Continued task blocking user interface thread

I am writing a continuous polling cycle to observe some events and then take some actions in the user interface thread.

I am writing the following code

public static void HandlePopup(this HostedControl control, string className, string caption, System.Action callback) { var popupTask = Task.Factory.StartNew(() => { Thread.Sleep(5000); // just wait for 5 seconds. }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).ContinueWith((prevTask) => { AutomationElementCollection collection = null; do { } while (true); }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).ContinueWith((prevTask) => { if (!prevTask.IsFaulted) { if (control.InvokeRequired) { control.Invoke(callback); } else { callback(); } } }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); try { ////popupTask.Wait(); } catch (AggregateException ex) { ex.Handle(exnew => { return true; }); } } 

There is no code in the do while loop because I want to check that if I run the loop endlessly, the user interface is not blocked, however it does not work as expected, and when the code starts this loop (which will never be returned) the user interface it freezes and becomes immune until I break the run.

What should I do to make it work quietly in the background,

Note. The parent from which this method is called is the s documentcompelte` web browser control. The web browser control is inside the Windows Forms application.

+6
source share
1 answer

You explicitly say that the continuation starts in the current synchronization context by specifying

 TaskScheduler.FromCurrentSynchronizationContext() 

So yes, this will block the user interface thread because it works in the user interface thread, assuming that this generic method is invoked in the user interface thread. The initial task will run in the background, but your sequels are scheduled to run in the user interface thread. If you do not want to do this, do not use this task scheduler.

+14
source

All Articles