I have the following function that was originally being invoked from the UI (Main) thread:
private void BreakToggle(int line, Boolean toggle)
{
string flag;
if (toggle)
{
flag = "0"; //Add
}
else
{
flag = "1"; //Delete
}
string logicLine = line.ToString();
SetLogicBreakLineResponse response = ddcdao.SetLogicBreakLine(logicName, logicLine, flag);
}
However, the bottom line tries to establish connection with an electronic device and send a signal, which can take upto 5 seconds if the connection is slow. So to prevent the UI from hanging, I decided to make a separate thread to handle this.
This function can also be called many times in a short period of time (say 10 times within 1 second), so I figured instead of having a backgroundworker to take care of this, I should use Threadpool so I modified my code like so:
ThreadPool.QueueUserWorkItem(state =>
{
SetLogicBreakLineResponse response = ddcdao.SetLogicBreakLine(logicName, logicLine, flag);
});
Is that the proper way of using Threadpool? I feel like I’m definitely doing something wrong if using threads is this easy. Will this code cause any unknown voodoo to my application?
Your example is a reasonable start for using the thread pool. It can be as easy as that if the only thing you are interested in is just getting the code to run outside your UI thread.
However, you should be aware of differences in behavior between your original code and the multithreaded version:
You do need to think about these differences, but if there’s nothing wrong with the MT behavior then it’s simply as easy as that.