I’ve created a class library which has a method to query for open ports, and in some cases can take up to 3 seconds to complete. If I were to implement this in a separate thread, would this be handled in my class method, or would it be done by the highest entity for example the main form?
Could you provide examples where threads are handled internally within a class?
[EDIT]
Here’s the method in question.
public void QueryOpenPorts(out string[] portNames, out bool[] isOpen)
{
// get valid ports on computer
portNames = QueryPortNames();
// number of ports
int count = portNames.Length;
// initialise isOpen array
isOpen = new bool[count];
// iterate through ports and test connection
for (int i = 0; i < count; i++)
{
using (SerialPort serialPort = new SerialPort(portNames[i]))
{
serialPort.Open();
// port is available
isOpen[i] = true;
}
}
}
Architecturally, I’d create a thread from the main form that will call your class library. Who knows, maybe some other class calling your library does not need the call to be in a thread.
Within my main class i have something like:
And CheckSessions goes off to call whatever it needs.
I also use background workers to do my work that requires long delays with the web server:
The anonymous function within my worker DoWork actually uses my web service wrapper to make web service calls.
However, before doing things like this, i REALLY recommend you to give this a read:
http://www.albahari.com/threading/