简体   繁体   中英

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

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.

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.

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