问题
I am connecting to Gmail account using TCP client for reading emails. It returns SslStream for the TCP connection. It works fine for single thread environment but performance is very poor in terms of speed.
I need to optimize the project so that its speed can be increased. I have implemented multithreading which increases the speeed but application gets hang at some point.
Is it thread safe to use TCP connection (global member)?
OR Can I create multiple TCP connections and pass to the thread method to increase the speed ?
OR is there any other better way for doing this?
TCPClient m_TCPclient
SslStream sslStream;
private void createTCP()
{
// creating tcp and sslstream
}
private void authenticateUser()
{
// authenticating the user
}
private void getUserdata()
{
// iterating folders and its items
foreach(string emailID in IDList)
{
//Thread implementation
}
回答1:
With regard to thread safety, take a quick glance at the documentation for the TcpClient and SslStream:
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
I think what you may want to look at is using the Asynch methods of the stream to deal with the hanging when you perform IO.
回答2:
Neither TCPClient nor SslStream objects are thread safe. You would have to add thread synchronization to avoid race conditions to avoid hanging. However, your application speed will still be dependent on the single tcp client which essentially renders your multi threading useless in terms of tcp throughput.
Have each thread create its own connection and stream objects instead. This will in turn increase your tcp throughput which is most likely the bottleneck of your application.
To synchronize the threads so they don't read the same information, have the main thread fetch a list of emails and pass a subset of the email list to each of the threads which in turn fetch those emails using their own connections.
You can also use caching to avoid getting the same information every time you restart the application.
来源:https://stackoverflow.com/questions/28345677/tcp-client-through-multithreading-in-c-sharp