This project is read-only.

Unresponsive UI when running task in OnNavigatedTo?

May 19, 2013 at 1:50 AM
Hi, I have recently run into a strange problem. If i write a piece of code like this, the UI is unresponsive and freezes for 20 seconds:
        public void OnNavigatedTo(FirstFloor.ModernUI.Windows.Navigation.NavigationEventArgs e)
        {
            var s= Stopwatch.StartNew();
            Console.WriteLine("start");
            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(20000);
                Console.WriteLine("end task:"+ s.Elapsed.TotalSeconds);
            }, TaskCreationOptions.LongRunning);
            Console.WriteLine("end:" + s.Elapsed.TotalSeconds);
         }
However, If i write it like this, the UI is responsive immediately:
        public void OnNavigatedTo(FirstFloor.ModernUI.Windows.Navigation.NavigationEventArgs e)
        {
            var s= Stopwatch.StartNew();
            Console.WriteLine("start");
            new Thread(new ThreadStart(()=>{
                Thread.Sleep(20000);
                Console.WriteLine("end task:" + s.Elapsed.TotalSeconds);
            })).Start();
            Console.WriteLine("end:" + s.Elapsed.TotalSeconds);
        }
In both cases, the console output is the same. "start" and "end" are printed instantaneously and then "end task" is printed 20 seconds later. I can not explain this behavior. I have just started using this library and do not know what is going on.
May 20, 2013 at 3:20 PM
Task.Factory.StartNew does not necessarily imply the task will run in a background thread. You'll need to supply the TaskScheduler.Default as scheduler explicitly like so:
Task.Factory.StartNew(() => { .. }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
May 20, 2013 at 6:38 PM
Edited May 20, 2013 at 6:38 PM
I was under the impression that the "Default" task scheduler was the default on new tasks. After more research I see that it can be either Current or Default depending on the situation if not specified. Sorry for the question.