TPL如何执行“回访” [英] TPL How to Perform a 'Call-Back'
问题描述
我有一个小的应用程序,需要测试SQL连接字符串的连接数(每完成一处,一时间)。要做到这一点,我将 ConnectionTimeout = 5
暂时避免了漫长的等待,如果连接无效, ConnectionTimeout = 0
(永远等待)说。
要避免UI挂,而我们试图打开()
坏连接(甚至与 ConnectionTimeout = 5
的等待的SQLException
可长达二十秒为单位),我要运行使用任务并行库(TPL)一个单独的线程测试。所以我剥离我的新主题,如:
任务<布尔> asyncTestConn = Task.Factory.StartNew<布尔>
(()=> TestConnection(康涅狄格州,bShowErrMsg));
返回asyncTestConn.Result;
的问题是,这仍然是锁定的用户界面(明确),因为它正在等待结果之前返回到调用者。如何允许代码同时从异步工作
?
$得到最终的结果控制返回到UI(释放的GUI) b $ b
此外,从内工作
我能做到合法 MessageBox.Show(一些信息)
?这不适用于 BackgroundWorkers
工作和汇集线程是默认后台线程;但它似乎并不成为一个问题。感谢您的时间
您是对的,这是在等待发生的:
收益asyncTestConn.Result;
您可以简单地建立在TestConnection(尾部的精达代码)或使用继续:
//未经检验的
//任务<布尔> asyncTestConn = Task.Factory.Create<布尔> (
任务<布尔> asyncTestConn =新任务<布尔>(
()=> TestConnection(康涅狄格州,bShowErrMsg));
asyncTestConn.ContinueWith(MyFinishCode);
asyncTestConn 。开始()
我可以做合法
MessageBox.Show(一些信息)
?
块引用>
其实是,在MessageBox是线程安全的。应尽可能从BGW为好。
但你用了很多延长工作寿命,这不是一个好主意。
I have a small application that needs to test SQL connection strings for a number of connections (each done one-at-a-time). To do this I set the
ConnectionTimeout = 5
temporarily to avoid a long wait if the connection is not valid andConnectionTimeout = 0
(wait forever), say.To avoid the UI hanging whilst we attempt to
Open()
a bad connection (even withConnectionTimeout = 5
the wait for theSqlException
can be up to twenty seconds), I want to run the test on a separate thread using Task Parallel Library (TPL). So I spin-off my new thread like:Task<bool> asyncTestConn = Task.Factory.StartNew<bool> (() => TestConnection(conn, bShowErrMsg)); return asyncTestConn.Result;
The problem is that this is still locking the UI (clearly), as it is waiting for the result before returning to the caller. How do I allow the code to return control to the UI (freeing up the GUI) whilst getting the eventual result from the asynchronous
Task
?Also, from within a
Task
can I legitimately doMessageBox.Show("Some message")
? This does not work forBackgroundWorkers
and this pooled-thread is a background thread by default; yet it does not seem to be a problem. Thanks for your time.解决方案You are right, this is where the waiting happens:
return asyncTestConn.Result;
You could simply build the finish-up code in the tail of TestConnection() or use a Continuation:
// untested //Task<bool> asyncTestConn = Task.Factory.Create<bool> ( Task<bool> asyncTestConn = new Task<bool> ( () => TestConnection(conn, bShowErrMsg)); asyncTestConn.ContinueWith(MyFinishCode); asyncTestConn.Start()
can I legitimately do
MessageBox.Show("Some message")
?Actually Yes, the MessageBox is thread-safe. Should be possible from a Bgw as well.
But you are prolonging the life of the Task by a lot, it's not a good idea.
这篇关于TPL如何执行“回访”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!