C# endless list is filled and taken - concept with BlockingCollection<T> Class and xml messages

Markus Freitag 3,786 Reputation points
2020-12-23T08:39:07.03+00:00

Hello,
system.collections.concurrent.blockingcollection-1

I am looking for an example of C# WPF.

The data XML is permanently added to and taken from a list. This is done asynchronously. Several messages XML can be added than taken.

Summary
Data is permanently added and processed. Yes must be a queue, because adding may be faster than processing.

<message date="23.12.2020 09:23am">  
  <body>  
    <invoices>  
      <invoice eventid="644cb449-82bf-4243-89bd-2d69a40ff306" number="123"  processed="false">  
        <name>Jürgen Bauer</name>  
      </invoice>  
      <invoice eventid="93897c34-850f-4d00-ab15-d16254ea5f4c" number="456" processed="false">  
        <name>Jürgen Maier</name>  
      </invoice>  
      <invoice eventid="80782086-801a-4645-aebe-915c50e3cd1a" number="789" processed="false">  
        <name>Michael Brown</name>  
      </invoice>  
    </invoices>  
  </body>  
</message>  

Here three items inside list.

I take the first make something, set it to true and send to the next process step.

<invoice eventid="93897c34-850f-4d00-ab15-d16254ea5f4c" number="456" processed="true">  
            <name>Jürgen Maier</name>  
</invoice>  
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,011 questions
{count} votes

Accepted answer
  1. Timon Yang-MSFT 9,591 Reputation points
    2020-12-25T08:36:29.643+00:00

    The final result I got is not much different from the answers you got in other threads, and it may disappoint you a bit.
    I'm thinking about whether you really need to use async-await.
    Your current problem is a multi-producer single-consumer situation.
    Couldn't the producer call a simple Add method and the consumer call the Take method?
    Are there any unexpected errors in your actual tests?
    Update:
    It might look like this:

        public partial class MainWindow : Window  
        {  
            public MainWindow()  
            {  
                InitializeComponent();  
            }  
            TcpListener server;  
            BlockingCollection<root> bc;  
            public void InitListening()  
            {  
                bc = new BlockingCollection<root>();  
                Int32 port = 13000;  
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");  
                server = new TcpListener(localAddr, port);  
            }  
           
            public void Add(root data)  
            {  
                Task t2 = Task.Run(() =>  
                {  
                    bc.Add(data);  
                });  
            }  
      
            public void Take()  
            {  
                Task.Run(() =>  
                {  
                    try  
                    {  
                        while (true)  
                        {  
                            Console.WriteLine("Take" + bc.Take());  
                        }  
                    }  
                    catch (Exception e)  
                    {  
                        Console.WriteLine(e.Message);  
                    }  
                });  
            }  
      
            private void StartLisBtn_Click(object sender, RoutedEventArgs e)  
            {  
      
                server.Start();  
      
                Byte[] bytes = new Byte[256];  
                String data = null;  
                Task.Run(() =>  
                {  
                    while (true)  
                    {  
                        Console.Write("Waiting for a connection... ");  
      
                        TcpClient client = server.AcceptTcpClient();  
                        Console.WriteLine("Connected!");  
      
                        data = null;  
      
                        NetworkStream stream = client.GetStream();  
                        int i;  
      
                        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)  
                        {  
                            data = Encoding.ASCII.GetString(bytes, 0, i);  
                            Console.WriteLine("Received: {0}", data);  
      
                            XmlSerializer serializer = new XmlSerializer(typeof(root));  
                            MemoryStream memStream = new MemoryStream(bytes);  
                            root result = (root)serializer.Deserialize(memStream);  
                            Add(result);  
                        }  
                        client.Close();  
                    }  
                });  
            }  
      
            private void StopLisBtn_Click(object sender, RoutedEventArgs e)  
            {  
                server.Stop();  
            }  
      
            private void TakeBtn_Click(object sender, RoutedEventArgs e)  
            {  
                Take();  
                //If you need to write changes to the xml file, enable the following code.  
      
                //XmlDocument doc = new XmlDocument();  
                //doc.Load(@"D:\test\xml\out.xml");  
                //XmlNode root = doc.DocumentElement;  
                //XmlNodeList myNodeList = root.SelectNodes("//book/title");  
                //XmlNode myNode = myNodeList.Cast<XmlNode>().Where(n => n.Attributes["pro"].Value == "false").FirstOrDefault();  
                //myNode.Attributes[0].Value = "true";  
                //doc.Save(@"D:\test\xml\out.xml");  
            }  
        }  
    

    But there may be some omissions in the actual situation. If an error occurs, we can discuss the specific error.


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.