简体   繁体   中英

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 control s documentcompelte` event. The web browser control is inside windows forms application.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM