如何优雅地重新启动任务
本文关键字:任务 重新启动 何优雅 | 更新日期: 2023-09-27 18:10:22
所以我有这样的东西:
Task.Factory.FromAsync<TcpClient>(tcpListener.BeginAcceptTcpClient, tcpListener.EndAcceptTcpClient, tcpListener).ContinueWith(ConnectionAccepted);
private void ConnectionAccepted(Task<TcpClient> tcpClientTask)
{
TcpClient tcpClient = tcpClientTask.Result;
// Do something with tcpClient
}
现在我想知道,如何在此方法结束时再次启动Task.Factory.FromAsync<TcpClient>(...)
?我不能只是复制粘贴这行代码,因为我没有访问TcpListener的权限,也不想让它成为成员变量。即使我写了,这一行代码也太长了,对我来说有点像代码重复。
任务框架是否提供某种机制来完成此任务?
谢谢。
如svick所建议的,最简单的方法是使tcpListener
进入一个字段。但是如果由于某些原因你不能这样做,试试这个模式:
void AcceptClient()
{
// Create tcpListener here.
AcceptClientImpl(tcpListener);
}
void AcceptClientImpl(TcpListener tcpListener)
{
Task.Factory.FromAsync<TcpClient>(tcpListener.BeginAcceptTcpClient, tcpListener.EndAcceptTcpClient, tcpListener).ContinueWith(antecedent =>
{
ConnectionAccepted(antecedent.Result);
// Restart task by calling AcceptClientImpl "recursively".
// Note, this is called from the thread pool. So no stack overflows.
AcceptClientImpl(tcpListener);
});
}
void ConnectionAccepted(TcpClient tcpClient)
{
// Do stuff here.
}
我认为框架中没有任何东西可以重新启动Task
s。
但是您的问题可以通过将tcpListener
放入一个字段并将创建任务的行放入一个方法来简单地解决,因此不会有任何代码重复。