0

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.

Community
  • 1
  • 1
MoonKnight
  • 23,214
  • 40
  • 145
  • 277

1 Answers1

1

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.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
  • Thanks very much for your time. Do I have to dispose the `Task` or will it be 'garbage collected' in the loosest sense of the term? – MoonKnight Mar 08 '12 at 14:23
  • 1
    unless you are using event handles you won't have to dispose the `Task` - also see http://stackoverflow.com/questions/3734280/is-it-considered-acceptable-to-not-call-dispose-on-a-tpl-task-object – BrokenGlass Mar 08 '12 at 14:25