Azure / DotNetty

DotNetty project – a port of netty, event-driven asynchronous network application framework
Other
4.07k stars 971 forks source link

How to solve the program freezing when calling bootstrap.BindAsync(localAddress).Result in Unity? #610

Open Siwen opened 1 year ago

Siwen commented 1 year ago

How to solve the program freezing when calling bootstrap.BindAsync(localAddress).Result in Unity?

Code:

     private void init () {
        _executorPool = executorPool;
        _executorPool.CreateMessageExecutor();
        _eventLoopGroup = eventLoopGroup;
        _scheduleThread = new EventLoopScheduleThread();
        bootstrap = new Bootstrap();
        bootstrap.Group(_eventLoopGroup);
        bootstrap.ChannelFactory(() => new SocketDatagramChannel(AddressFamily.InterNetwork));
        bootstrap.Handler(new ActionChannelInitializer<SocketDatagramChannel>(channel =>
        {
            var pipeline = channel.Pipeline;
            pipeline.AddLast(new ClientChannelHandler(_channelManager,channelConfig));
        }));
     }

    private static IChannel bindLocal(Bootstrap bootstrap,EndPoint localAddress = null)
    {
        if (localAddress == null)
        {
            localAddress = new IPEndPoint(IPAddress.Any, 0);
        }

        // ------> program freezing <------
        return bootstrap.BindAsync(localAddress).Result;
    }
rekcah1986 commented 1 year ago

Same for me.

Buryyy commented 1 week ago

The freezing issue in your code occurs because you are calling .Result on a task returned by bootstrap.BindAsync(), which blocks the calling thread until the task completes. In Unity, blocking the main thread is problematic because Unity's game loop (and most UI-related tasks) runs on the main thread, which leads to freezing.