Tristan Cunningham
Tristan Cunningham

Reputation: 919

Winform how to deal with method freezing UI

I currently have a method that creates a string from variables that will be expanded with much more modes, and then it sends that string down a serial port. With the serial port writing enabled this freezes the UI, but without it, it runs fine.

private void OnTimedEvent(Object myObject, EventArgs myEventArgs)
    {            
        l = (l > 100) ? 100 : l;
        r = (r > 100) ? 100 : r;

        mRectangle1 = new RectangleF(13, 153, 80 * (l / 100), 16);
        mRectangle2 = new RectangleF(173 - (80 * (r / 100)), 153, 80 * (r / 100), 16);

        string start = "";

        for (int i = 0; i < 25; i++)
        {
            start += "0:" + Math.Round(255 * (l / 100)) + ":0;";
        }

        start += ".";
        port.Write(start);
        Invalidate();
    }

How would I best deal with this, so i can constantly send down the serial port without freezing UI?

Upvotes: 0

Views: 302

Answers (1)

Derek W
Derek W

Reputation: 10046

You can use the BackgroundWorker class to do this.

The DoWork event is where the potentially time consuming work is done on a background thread. You can pass the start argument to the RunWorkerAsync(object) method which fires up the DoWork event.

Quick example:

// start the work in the background thread like this
backgroundWorker1.RunWorkerAsync(start);

// handles the time-consuming task without blocking the UI thread
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{   
    string start = (string) e.Argument;
    port.Write(start);
}

Upvotes: 3

Related Questions