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.
source share