简体   繁体   中英

Is this Tcp async/await code considered thread safe?

I wrote some code using TcpListener and async/await which will wait for 3 clients to connect to the server, add them to a list, then do something with the clients:

private async void button1_Click(object sender, EventArgs e)
{
    var listener = new TcpListener(IPAddress.Any, 6015);
    listener.Start();
    var clients = await Task.Run(() => GetTcpClients(listener));

    // Do something with clients

    listener.Stop();
}

private static async Task<List<TcpClient>> GetTcpClients(TcpListener listener)
{
    var clients = new List<TcpClient>();
    var clientsMaxReached = false;

    while (!clientsMaxReached)
    {
        var client = await listener.AcceptTcpClientAsync();
        clients.Add(client);
        if (clients.Count == 3)
            clientsMaxReached = true;
    }

    return clients;
}

What I am concerned about is whether it's okay to use a List for the clients instead of a thread-safe collection, since the await may resume on a different thread. Also, just wondering if my TcpListener usage is thread safe too.

I don't see a problem since no two threads will ever access the list or TcpListener at the same time, but just thought I'd check.

Both the accesses to list and listener are thread safe.

The clients list is not accessed and accessible by anybody else until the list is completely built. Any code after await will not execute until the awaited task/method is completed.

For the listener it's pretty much the same but in opposite direction. The instance is passed to getTcpClients() method but any other access is blocked until this method stops working with the instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM