MoonKnight
MoonKnight

Reputation: 23833

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.

Upvotes: 0

Views: 158

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160882

This is perfectly fine, you are just starting a "fire and forget" task which will run on a thread-pool thread - however in the first example you seem to expect a result (I assume a boolean indicating whether the connection test was successful) - in the second you won't have any - unless your task e.g. raises an event or calls a predefined callback.

Upvotes: 1

Related Questions