如前所述,我继续研究我的 TCP 套接字今天早上 https://stackoverflow.com/questions/74812333.
我发现每次我通过这样的套接字发送消息时,套接字的数量都会不断增加。这仅仅意味着我不断创建和打开新的套接字,而不是重新使用已经打开的套接字。
在我的应用程序中,我有一个连接存储库,我只需要使用其中一个。但我担心我会不断地创造新的。这是它的完成方式:
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
导致在内部创建一个对象。
- As the
GetByName()
方法执行FirstOrDefault()
of a Where()
方法,这是给出已经存在的对象,并且它不会创建新的对象。
现在我的印象是 1. 是正确的,但 2. 是错误的,因为Connection Connection_For_Message
always创建对象的新实例。
我的印象是否正确?如果是,我该如何解决这个问题?我正在考虑改变Repository
从静态类变成单例,但我没有找到ISingleton
或某些东西System.Reflection
,还是我看错了方向?
Edit:特此构造函数的一部分Conn
class:
public Conn(...)
{
...
TcpConnection = new TcpConnection(...); // in here a
...
}
就TcpConnection
类涉及:
public class TcpConnection : IDisposable
{
public Socket _socket;
...
每次发消息都会经过GetByName()
方法和我的调用堆栈如下所示:
My_Application.dll!TcpConnection.TcpConnection(...) Line 39 C#
> My_Application.dll!Conn.Conn(...) Line 32 C#
[External Code]
My_Application.dll!ConnectionRepository.GetByName(string name, ...) Line 71 C#
该行,标记为>
是构造函数,这确实证明了GetByName()
正在呼叫Conn
确实是构造函数。 (哦,为什么之间有“外部代码”GetByName()
方法和构造函数?)
再次编辑:我已成功显示外部代码,因此选中了“显示外部代码”的调用堆栈:
> 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#