【发布时间】:2020-08-26 00:28:06
【问题描述】:
我创建了一个新的 .NET Core 辅助服务项目。此服务还应充当 TCP 套接字服务器并侦听传入消息。所以基于the code sample from the docs这就是我基本上在做的事情
public class Worker : BackgroundService
{
public override async Task StartAsync(CancellationToken cancellationToken)
{
TcpListener tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1234);
tcpListener.Start();
try
{
while (true)
{
TcpClient tcpClient = await tcpListener.AcceptTcpClientAsync();
NetworkStream tcpClientStream = tcpClient.GetStream();
using StreamReader streamReader = new StreamReader(tcpClientStream);
string messageText = await streamReader.ReadToEndAsync();
// ... do things with messageText ...
}
}
catch (Exception exception)
{
// ... error handling ...
}
await base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
}
}
}
ExecuteAsync 方法将不再被调用,因为代码卡在StartAsync 方法中的while 循环中。当我注释掉整个覆盖 StartAsync 方法时,一切正常,ExecuteAsync 方法被调用。
是否有可能摆脱阻塞的while循环并使用事件处理程序或类似的东西?
【问题讨论】:
-
await tcpListener.AcceptTcpClientAsync()将阻塞直到有连接,所以你很可能不想在那里做。可能将其移至ExecuteAsync或从ExecuteAsync调用的单独方法? -
这似乎本质上是the same question you already posted and deleted。 请勿转发问题。如果您对您发布的问题收到的回复感到失望,处理它的正确方法是改进原始问题。重新发布相同的问题违反了 Stack Overflow 社区准则,而且会适得其反。
标签: c# .net-core tcplistener