Dispose Stream socket listener in UWP

Subazzz 1 Reputation point
2019-12-09T07:00:09.217+00:00

I have implemented two apps to run as server and client using stream sockets. It shares files from server app to multiple client apps when user is clicked on sharing option in Server app. I need to close sockets and socket listener when each operation is done. Sockets can be closed when each operations are competed.
There can be a scenario, Server app share only one file for the day. So I need to close the stream socket listener also.

What is best place to close the stream socket listener? Is there any best practice to follow.

Thanks in advance.

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,851 Reputation points
    2019-12-09T09:39:57.473+00:00

    What is best place to close the stream socket listener? Is there any best practice to follow.

    In general, we often make Dispose method for socket tool class, we could call StreamSocket.Dispose() then call StreamSocketListener.Dispose() at same time we need also to remove ConnectionReceived event handler

    public async override void Dispose()  
    {  
       clientSocket.Dispose();  
        
        Listener.ConnectionReceived -= OnConnection;  
        Listener?.CancelIOAsync();  
        Listener.Dispose();  
        Listener = null;  
    }