I am attempting to create a method that accepts TcpClient connections and performs a task once a client is connected, "ConnectedAction". I am receiving a compile error when trying to have a new task created to run the delegate "ConnectedAction".
我正在尝试创建一个接受TcpClient连接的方法,并在客户端连接后执行任务“ConnectedAction”。我在尝试创建一个新任务来运行委托“ConnectedAction”时收到编译错误。
Argument 1: cannot convert from 'void' to 'System.Func'
参数1:无法从'void'转换为'System.Func'
I believe that this error is because the method is trying to run the "ConnectedAction" method and return void to the Task.Run parameter.
我相信这个错误是因为该方法试图运行“ConnectedAction”方法并将void返回给Task.Run参数。
How do I have the Task run the "ConnectedAction" delegate?
如何让Task运行“ConnectedAction”委托?
class Listener
{
public IPEndPoint ListenerEndPoint {get; private set;}
public int TotalAttemptedConnections { get; private set; }
public Action<TcpClient> ConnectedAction { get; private set; }
public Listener(IPEndPoint listenerEndPoint, Action<TcpClient> connectedAction)
{
ConnectedAction = connectedAction;
ListenerEndPoint = listenerEndPoint;
Task.Factory.StartNew(Listen, TaskCreationOptions.LongRunning);
}
private void Listen()
{
TcpListener tcpListener = new TcpListener(ListenerEndPoint);
tcpListener.Start();
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
TotalAttemptedConnections++;
//Error here
Task.Run(ConnectedAction(tcpClient));
}
}
}
1 个解决方案
#1
15
You should write:
你应该写:
Task.Run(() => ConnectedAction(tcpClient));
This creates a lambda function that takes no parameters and will call your specified function with the correct argument. The lambda is implicitly wrapped into the delegate type needed by the Task.Run
parameters.
这将创建一个不带参数的lambda函数,并使用正确的参数调用指定的函数。 lambda隐式包装到Task.Run参数所需的委托类型中。
What you wrote calls the function and then attempts to turn the return value of the function into a delegate.
您编写的内容调用该函数,然后尝试将函数的返回值转换为委托。
#1
15
You should write:
你应该写:
Task.Run(() => ConnectedAction(tcpClient));
This creates a lambda function that takes no parameters and will call your specified function with the correct argument. The lambda is implicitly wrapped into the delegate type needed by the Task.Run
parameters.
这将创建一个不带参数的lambda函数,并使用正确的参数调用指定的函数。 lambda隐式包装到Task.Run参数所需的委托类型中。
What you wrote calls the function and then attempts to turn the return value of the function into a delegate.
您编写的内容调用该函数,然后尝试将函数的返回值转换为委托。