2012-01-16 42 views
2

哪種更自然的方式來啓動一個MS TPL的Task類實例,並延遲一段時間?如何啓動MS TPL的任務類實例有一些延遲?

Task logManager = Task.Factory.StartNew(() => { // Some code }, TaskCreationOptions.LongRunning); 

我只是想在幾秒鐘後開始吧...

謝謝!

+0

相關:http://stackoverflow.com/questions/4990602/what-is-the-correct-way-to-delay-the-start-of-a-task-in-c-sharp – DuckMaestro 2012-02-21 07:05:05

回答

3

使用一個定時器,所以你不會在延遲時間浪費螺紋加工時間:

Task logManager = null; 
new Timer((state) => 
    { 
     logManager = Task.Factory.StartNew(() => { /* Some code*/}, TaskCreationOptions.LongRunning); 
    }, null, TimeSpan.FromSeconds(2), TimeSpan.FromMilliseconds(-1)); 
+1

我認爲你的解決方案是最好的! – 2012-01-16 17:44:08

1
Task logManager = Task.Factory.StartNew(() => { Thread.Sleep(1000); }, TaskCreationOptions.LongRunning); 

​​將使用一個專門的線程在這種情況下,使阻塞不會影響任何其他線程

2
int msDelay = 1000; 
Task task = Task.Factory 
    .StartNew(() => { Thread.Sleep(msDelay); }) 
    .ContinueWith((Task starter) => { MessageBox.Show("Started after delay"); }, , TaskContinuationOptions.LongRunning);