Using NetMQ to receive data in a C# application

272 Views Asked by At

I'm having trouble making a simple test app that uses NetMQ to receive data from an established network. I'd like to eventually do things with this data, but for now I just need to get basic receiving working. The code is below:

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        textOut.Text = "";


        var utf8 = new UTF8Encoding();

        using (var client = new SubscriberSocket())
        {
            client.Options.ReceiveHighWatermark = 1000;
            client.Connect("tcp://eddn.edcd.io:9500");
            client.SubscribeToAnyTopic();
            while (true)
            {
                var bytes = client.ReceiveFrameBytes();
                var uncompressed = ZlibStream.UncompressBuffer(bytes);

                var result = utf8.GetString(uncompressed);

                textOut.Text += result;
                //Console.WriteLine(result);
                Thread.Sleep(10);
            }
        }

    }

    
}

When I run this, I see it is doing things in the performance monitor, but the window doesn't come up.

Before I added the NetMW code, the window displayed just fine so I don't think it is a problem with window visibility or anything like that. Any advice on what's going wrong here and how it might be fixed would be greatly appreciated.

1

There are 1 best solutions below

0
On

Your immediate problem is you have a tight loop.

This:

        while (true)
        {
            var bytes = client.ReceiveFrameBytes();
            var uncompressed = ZlibStream.UncompressBuffer(bytes);

            var result = utf8.GetString(uncompressed);

            textOut.Text += result;
            //Console.WriteLine(result);
            Thread.Sleep(10);
        }

Will run forever.

This is a bad thing.

That loop is running on the UI thread.

This is the thread that does everything.

That includes showing your window.

This problem is compounded by the fact you put that tight loop in your main window constructor.

Don't put substantial code in any UI object constructor. When it fails your ui object will not be constructed.

If that code really needs to loop forever then your socket reading code should be run on a background thread.

That aspect of the question is netmq specific rather than wpf but I would have thought you can open a socket and subscribe a handler which will act as data is received.