Alexander Sacco
Alexander Sacco

Reputation: 13

If statement getting passed over

The if statement in my code isn't working, it always goes straight to the else, I know for sure the value IS 255 but it still won't go to if, I even tried testing it in the else and it reported back that it IS 255 so I don't know why it keeps doing this, im just really confused now, can someone help?

public Form1()
{
    InitializeComponent();
    serialPort1.Open();
    string lastLine = string.Empty;

    Task.Run(() =>
    {
        while (true)
        {
            string tailValue = lastLine;
            lastLine = serialPort1.ReadLine();
            string line = lastLine;

            label1.BeginInvoke(new Action(() =>
            {
                label1.Text = string.IsNullOrEmpty(line) || string.Equals(tailValue, line)
                    ? label1.Text
                    : $"{line}";
            }));

            if (label1.Text == "255")
            {
                Console.WriteLine(label1.Text);
                System.Diagnostics.Process.Start("http://www.google.com");
                Task.Delay(10000).Wait();
            }

            Task.Delay(1000).Wait();
        }
    });
}

Upvotes: 0

Views: 65

Answers (1)

Kolichikov
Kolichikov

Reputation: 3020

What's happening here is that you are executing asynchronous code, but not waiting for the result to be calculated before trying to use it.

Here's the documentation for BeginInvoke. Note the description:

Executes the specified delegate asynchronously on the thread that the control's underlying handle was created on.

So when the call to BeginInvoke happens, the next statement (in your case it's the if statement) is executed without waiting for your Action to complete.

So what is the value of label1 before you execute Action? (it's probably not 255)

One way of fixing this would be to use Invoke instead of BeginInvoke - you're already encasing this in Task.Run, so why are you trying to start another asynchronous call, especially for what looks like a simple calculation that the very next method depends on.

The reason Invoke works is because unlike BeginInvoke, it's a synchronous call. The calling thread blocks until Invoke finishes.

Upvotes: 1

Related Questions