所以我有这样的东西:
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,也不想让它成为成员变量。即使我这样做了,这也是一行很长的代码,对我来说有点像是代码重复。
Tasks框架是否提供了某种机制来实现这一点?
谢谢。
发布于 2011-10-01 11:37:15
正如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.
}发布于 2011-10-01 11:16:03
我不认为框架中有任何东西可以重启Task%s。
但是您的问题可以很容易地解决,只需将tcpListener放入字段中,将创建任务的行放入方法中,这样就不会有任何代码重复。
https://stackoverflow.com/questions/7617645
复制相似问题