通过C#中的多线程进行TCP客户端 [英] TCP Client through multithreading in C#

查看:862
本文介绍了通过C#中的多线程进行TCP客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TCP客户端连接到Gmail帐户以阅读电子邮件.它为TCP连接返回SslStream.它在单线程环境中运行良好,但是在速度方面性能却很差.

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.

使用TCP连接(全局成员)是否线程安全?

Is it thread safe to use TCP connection (global member)?

或者我可以创建多个TCP连接并传递给线程方法以提高速度吗?

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

}

推荐答案

TCPClient和SslStream对象都不是线程安全的.您将必须添加线程同步以避免竞争条件以避免挂起.但是,您的应用程序速度仍将取决于单个tcp客户端,这实际上会使您的多线程在tcp吞吐量方面毫无用处.

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.

让每个线程创建自己的连接并流对象.反过来,这将增加您的tcp吞吐量,这很可能是应用程序的瓶颈.

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.

这篇关于通过C#中的多线程进行TCP客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆