简体   繁体   English

这个 Tcp async/await 代码被认为是线程安全的吗?

[英]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:我使用 TcpListener 和 async/await 编写了一些代码,它们将等待 3 个客户端连接到服务器,将它们添加到列表中,然后对客户端执行某些操作:

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.我担心的是是否可以为客户端使用 List 而不是线程安全集合,因为 await 可能会在不同的线程上恢复。 Also, just wondering if my TcpListener usage is thread safe too.另外,只是想知道我的 TcpListener 使用是否也是线程安全的。

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.我没有看到问题,因为没有两个线程会同时访问列表或 TcpListener,但只是想我会检查。

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.在完全构建列表之前,任何其他人都无法访问和访问clients列表。 Any code after await will not execute until the awaited task/method is completed.在等待的任务/方法完成之前,await 之后的任何代码都不会执行。

For the listener it's pretty much the same but in opposite direction.对于listener来说,它几乎相同,但方向相反。 The instance is passed to getTcpClients() method but any other access is blocked until this method stops working with the instance.该实例被传递给getTcpClients()方法,但在此方法停止使用该实例之前,任何其他访问都会被阻止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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