简体   繁体   中英

Working with TPL Using Embedded Tasks

I am running a process on a separate thread to facilitate concurrency and a smooth user interface calling

private void ThreadedTestConnection(SqlConnection conn, bool bShowErrMsg)
{
    Task<bool> asyncTestConn = Task.Factory.StartNew<bool> 
        (() => TestConnection(conn, bShowErrMsg)); 
    return asyncTestConn.Result;
    asyncTestConn.Dispose();
}

from the UI thread. However, the 'wait' caused by return asyncTestConn is stopping the UI thread being release back to the GUI. I have come up with the following fix. From an event fired from the GUI I have (not including try / catch blocks)

private void SomeClick_Event(object sender, EventArgs e)
{
    Task testConnection = Task.Factory.StartNew
        (() => UtilsDB.ThreadedTestConnection(mainConn, true));
}

This works. That is, it returns control to the GUI immediately whilst running the test on a seperate background thread. Am I being a very foolish boy in doing this, or is this Okay?

Note: This is a seperate question but related to this one I have not recived a satasfactory answer for.

很好,您只是在启动一个“即发即弃”任务,该任务将在线程池线程上运行-但是,在第一个示例中,您似乎期望得到一个结果(我假设是一个布尔值,指示连接测试是否成功) -第二秒钟您将没有任何内容-除非您的任务(例如引发事件或调用预定义的回调)。

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