2015-04-12 61 views
3

我想安排一個功能,每分鐘執行一次。這個方法調用一個HttpWebRequest的異步函數。我正在使用異步/等待策略:System.Threading.Timer與異步/等待重複卡住

var timer = new System.Threading.Timer(async (e) => 
{ 
    RSSClient rss = new RSSClient(listBoxRSS); 
    RSSNotification n = await rss.fetch(); 
    // ... 
    Console.WriteLine("Tick"); 
}, null, 0, 5000); 

控制檯打印「滴答」,但只有一次。看起來定時器由於某種原因卡住了。

取出異步/ AWAIT代碼後計時器工作正常,但:

var timer = new System.Threading.Timer((e) => 
{ 
    Console.WriteLine("Tick"); 
}, null, 0, 5000); 

爲何不重複,我怎麼能實現使用System.Threading.Timer異步/ AWAIT策略?

+1

你嘗試把'嘗試/ catch'你的計時器代碼裏面?也許它會在隨後的調用中拋出異常。 –

回答

5

正如Darin Dimitrov指出的那樣,異步方法內部有一個異常,出於某種原因,它在調試器中沒有顯示,但可以使用try/catch捕獲。

下面的代碼使用異步/等待工作正常:

var timer = new System.Threading.Timer(async (e) => 
{ 
    await Task.Delay(500); 
    Console.WriteLine("Tick"); 
}, null, 0, 5000);