【问题标题】:How to access a single concurrent queue from different threads / classes如何从不同的线程/类访问单个并发队列
【发布时间】:2015-05-19 20:12:37
【问题描述】:

我希望在这个问题中有足够的细节。

概述: 我的任务是从 TCP 流中获取数据并将数据显示在 gui 上,并格式化数据并将其写入文件。我可以单独完成所有项目,但我无法将它们粘合在一起。

在我的 main 我调用我的 tcp_listener

MyTcpListener.start();

MyTcpListener 不断循环读取数据

 public class MyTcpListener
{

    //public string start(ref CQ.ConQueue init_concurrent_queue)
    public static void start()
    {
        TcpListener server = null;

        try
        {
            // Set the TcpListener on port 13000.
            Int32 port = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();
            ....
           while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    // Translate data bytes to a ASCII string.
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                    Console.WriteLine("Received: {0}", data);

                    //  !!!  ADD DATA TO QUE HERE
                    Program.ConQueue

                    // Process the data sent by the client.
                    data = data.ToUpper();

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
                    data.ToString();

                    // Send back a response.
                    stream.Write(msg, 0, msg.Length);
                    Console.WriteLine("Sent: {0}", data);


                }

在上面的部分中,每当我获得新数据时,我都会将其写入控制台。但我需要做的是将它排入并发队列,我的其他类可以将其从队列中取出并写入文件。

我应该怎么做? 我应该在我的 main 中创建对象并通过引用我的其他线程/类来传递它吗?

或者有没有一种方法可以多次实例化对象,但在内存内部只创建一个队列并且所有对象都访问它?

【问题讨论】:

    标签: c# multithreading queue sharing


    【解决方案1】:

    您应该将队列传递给对象

    public string start(CQ.ConQueue queue)

    我不确定那个对象是什么,但 .NET 带有一个线程安全队列,ConcurrentQueue

    有一种想法,例如static 变量,无论您创建多少类实例,它都只有一个实例。将它们用于您的问题类型是不可取的,因为这不是它们的目的,它隐藏了对象之间的队列共享,并且绝对阻止您拥有多个队列。

    我注意到,您经过ref 这不是必需的。如果您在 C# 中传递 reference type,则有效地将指针传递给原始对象。通过ref 传递它具有不同的、更复杂的含义(您通过引用传递指针),我认为这不是您的意图。

    【讨论】:

      【解决方案2】:

      使用 ConcurrentQueue 类。它包含多线程操作所需的功能。

      信息:

      https://msdn.microsoft.com/en-us/library/dd267265%28v=vs.110%29.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-18
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多