You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免重复创建TCP连接对象?EF查询实例重复生成问题

TCP Socket连接复用问题排查与解决

我正在进行TCP Socket相关开发,发现每次通过Socket发送消息时,Socket数量持续增长,这说明我一直在创建并打开新Socket,而非复用已打开的连接。

我的应用里有一个连接仓库,原本只需要使用其中一个连接,但现在怀疑每次都在创建新实例。当前实现代码如下:

public static class Repository
{
  ...
  public static Conn GetByName(string name, ...)
  {
    return result = 
      context.Set<Conn>().Where(o => o.Name == name).FirstOrDefault();
  }
}

...
Conn Connection_For_Message = Repository.GetByName(request.ConnectionName, ...);

我原本的想法是:

  • Repository声明为static会在内部创建单一对象;
  • GetByName方法通过Where()+FirstOrDefault()会返回已有对象,不会创建新实例。

但现在我觉得第一条是对的,第二条错了,Connection_For_Message总是在创建新对象。我的判断是否正确?如果正确该怎么解决?我考虑过把Repository从静态类改成单例,但在System.Reflection里找不到ISingleton,是不是方向错了?

补充信息:
Conn类的部分构造函数如下:

public Conn(...)
{
    ...
    TcpConnection = new TcpConnection(...); // 这里会创建新的TcpConnection
    ...
}

TcpConnection类定义:

public class TcpConnection : IDisposable
{
    public Socket _socket;
    ...
}

每次发送消息调用GetByName时,调用栈显示触发了Conn和TcpConnection的构造函数,完整调用栈如下:

>  My_Application.dll!TcpConnection.TcpConnection(...) Line 39  C#
   My_Application.dll!Conn.Conn(...) Line 32    C#
   [Native to Managed Transition]   
   [Managed to Native Transition]   
   System.Private.CoreLib.dll!System.Reflection.RuntimeConstructorInfo.Invoke(System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object[] parameters, System.Globalization.CultureInfo culture)    C#
   System.Private.CoreLib.dll!System.RuntimeType.CreateInstanceImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture)   C#
   System.Private.CoreLib.dll!System.Activator.CreateInstance(System.Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes)    C#
   Castle.Core.dll!Castle.DynamicProxy.ProxyGenerator.CreateClassProxyInstance(System.Type proxyType, System.Collections.Generic.List<object> proxyArguments, System.Type classToProxy, object[] constructorArguments)  C#
   [Lightweight Function]   
   Microsoft.EntityFrameworkCore.Relational.dll!Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable<Conn>.Enumerator.MoveNext()   C#
   System.Linq.dll!System.Linq.Enumerable.TryGetSingle<Conn>(System.Collections.Generic.IEnumerable<Conn> source, out bool found)   C#
   [Lightweight Function]   
   System.Linq.Queryable.dll!System.Linq.Queryable.FirstOrDefault<Conn>(System.Linq.IQueryable<Conn> source)    C#
   My_Application.dll!ConnectionRepository.GetByName(string name, ...) Line 71  C#

内容的提问来源于stack exchange,提问作者Dominique

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:45:40