Runing one thread at a time on TaskScheduler (STA thread)

230 Views Asked by At

I have set StaTaskScheduler threads to 1 and I expected that I would get one Debug output every 5 seconds, but I end up with 10 with the same date

private void Test() {
    for (int i = 0; i < 10; i++)
        Task.Factory.StartNew(() =>
        {
            Task.Delay(5000); //temp for long operation
            Debug.WriteLine(DateTime.Now);
        }, CancellationToken.None, TaskCreationOptions.None, MainWindow.MyStaThread);
}

public static StaTaskScheduler MyStaThread = 
        new StaTaskScheduler(numberOfThreads: 1);

What am I missing? The reason for STA is that later it will be used for Icons extraction needing STA, but this test is to check it is done in sequence.

1

There are 1 best solutions below

1
oleksa On

you have to start tasks using the MyStaThred.QueueTask rather then Task.Factory.Startnew:

private void Test() {
    for (int i = 0; i < 10; i++)
        MyStaThread.QueueTask(new Task(() =>
        {
            Task.Delay(5000); //temp for long operation
            Debug.WriteLine(DateTime.Now);
        }));
}

public static StaTaskScheduler MyStaThread = 
        new StaTaskScheduler(numberOfThreads: 1);

Task.Factory.Startnew uses .Net Framework internal thread pool and does not take the StaTaskScheduler into account.