小编Jam*_*mon的帖子

如何使用Task.Run(Action <T>)

我正在尝试创建一个接受TcpClient连接的方法,并在客户端连接后执行任务"ConnectedAction".我在尝试创建一个新任务来运行委托"ConnectedAction"时收到编译错误.

参数1:无法从'void'转换为'System.Func'

我相信这个错误是因为该方法试图运行"ConnectedAction"方法并将void返回给Task.Run参数.

如何让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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

.net c# delegates compiler-errors task-parallel-library

12
推荐指数
1
解决办法
1万
查看次数