0

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.

Beep13
  • 11
  • 2
  • Never put substantial code in a UI object constructor. If it fails then your UI will not be constructed and you will have no window. Nothing to show the user "you got an error" in. Instead, you should subscribe to an event such as Loaded and put code in that. Then you will at least have a window up. You should also do something about error handling. I suggest you start with a globally handling unhandled errors. You need 4 or 5 handlers (google). – Andy Jul 08 '20 at 08:25

1 Answers1

0

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.

Andy
  • 11,864
  • 2
  • 17
  • 20