Task continuation blocking UI thread

Viewed 1125

I am writing a continuous polling loop to watch for some events to happen and then take some action on UI thread.

I am writing 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;
            });
        }
    }

The do while loop does not have any code now, because I want to test that if i run a loop infinitely the UI does not block, however , it is not working as expected and when the code runs this loop (which will never return) the UI freezes and becomes unresponsive untill i break the run.

What should i do to make it run silently in the background,

Note : the parent from where this method is called is a Web browser controlsdocumentcompelte` event. The web browser control is inside windows forms application.

1 Answers
Related