Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task continuation blocking UI thread

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.

like image 989
shashank Avatar asked Dec 17 '13 08:12

shashank


1 Answers

You're explicitly telling the continuation to run in the current synchronization context by specifying

TaskScheduler.FromCurrentSynchronizationContext()

So yes, that will block the UI thread because it's running in the UI thread assuming this overall method is called in a UI thread. The original task will run in the background, but your continuations are both scheduled to run in the UI thread. If you don't want to do that, don't use that task scheduler.

like image 130
Jon Skeet Avatar answered Nov 10 '22 00:11

Jon Skeet