我有一個小型應用程序需要測試多個連接(每個一次一個地完成)的SQL連接字符串。要做到這一點,我暫時設置ConnectionTimeout = 5
以避免連接無效並且等待很長時間(等待一段時間),比如說。TPL如何執行「回撥」
爲了避免UI掛,而我們試圖Open()
連接不良(即使ConnectionTimeout = 5
等待爲SqlException
可以達到二十秒爲單位),我想運行使用任務並行庫一個單獨的線程測試(TPL )。所以我分拆我的新主題,如:
Task<bool> asyncTestConn = Task.Factory.StartNew<bool>
(() => TestConnection(conn, bShowErrMsg));
return asyncTestConn.Result;
的問題是,這仍是鎖定UI(清晰),因爲它是返回給調用者之前等待結果。我如何讓代碼將控制返回給UI(釋放GUI),同時從異步Task
獲得最終結果?
另外,從Task
內我可以合法地做MessageBox.Show("Some message")
?這對BackgroundWorkers
不起作用,並且此池線程默認爲後臺線程;但它似乎不成問題。謝謝你的時間。
非常感謝您的回覆。整個想法是儘快回到UI/GUI的控制權,上述是如何實現的?如果我從一個名爲'ParrTestConn(SqlConnection conn,string bShowErrMsg)'的方法調用上述代碼,那麼我不能說'asyncTestConn.ContinueWith(ParrTestConn(conn,bShowErrMsg))'...或者我可以嗎? – MoonKnight 2012-03-08 12:31:55
@Killer你可以簡單地在開始()後返回。在使用這個GUI時,GUI應該保持響應。 – 2012-03-08 12:55:09
我沒有'Task.Factory.Create'方法可用? –
MoonKnight
2012-03-08 13:02:13