How to avoid freezing of GUI?

c# application hangs while running
c# form freezes while processing
winform freeze c#
c# windows forms application not responding
c# form show freezes
winforms not responding

i have a code which is like this :

private void testToolStripMenuItem_Click(object sender, EventArgs e)
{
    toolStripStatusLabel1.Text = " Device Testing...";

    positive = false;

    clearsensors_gui();
    datarec = false;
    cmd = 04;
    datarec = serialport_FT(0, 1);

    if (datarec)
    {
        char ab = Convert.ToChar(rec_data[1]);
        //MessageBox.Show("\n" + ab + "\n");
        int cab = Convert.ToInt16(ab);
        int cabc1 = cab & 1;
        int cabc2 = cab & 2;
        int cabc3 = cab & 4;
        int cabc4 = cab & 8;
        int cabc5 = cab & 16;
        int cabc6 = cab & 32;

        if (cabc1 == 1)
            ovalShape1.FillColor = Color.Green;
        else
            ovalShape1.FillColor = Color.Red;

        if (cabc2 == 2)
            ovalShape2.FillColor = Color.Green;
        else
            ovalShape2.FillColor = Color.Red;

        if (cabc3 == 4)
            ovalShape3.FillColor = Color.Green;
        else
            ovalShape3.FillColor = Color.Red;

        if (cabc4 == 8)
            ovalShape4.FillColor = Color.Green;
        else
            ovalShape4.FillColor = Color.Red;

        if (cabc5 == 16)
            ovalShape5.FillColor = Color.Green;
        else
            ovalShape5.FillColor = Color.Red;

        if (cabc6 == 32)
            ovalShape6.FillColor = Color.Green;
        else
            ovalShape6.FillColor = Color.Red;

        toolStripStatusLabel1.Text = " Device Tested";
    }
    else
    {
        toolStripStatusLabel1.Text = "Try Again or Communication With Device Failure....";
    }
}

the above code is to read a the sensors i.e datarec = serialport_FT(0, 1); function provides me a sensor output at the GUI side which'll be later depicted with red\green ovalShapeX(1-6)

Question: datarec = serialport_FT(0, 1); this function takes liltime and so the GUI freezes till that time how to avoid this?

i tried using background worker but didn't get where to put this whole process also encountered with cross-threaded operation error when it goes to ovalShape and changing its properties.

I'm not getting what part of the function to be used in the background and where and when to get back to the 1st thread

please help me to use backgroundworker or use invoke if i have to use Threading

You could do something like this:

toolStripStatusLabel1.Text = " Device Testing...";
positive = false;
clearsensors_gui();
datarec = false;
cmd = 04;

BackgroundWorker worker = new BackgroundWorker();

worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
    // Will be run on background thread
    args.Result = serialport_FT(0, 1);
};

worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
    bool result = (bool)args.Result;

    if (result)
    {
        // Do your UI updates here
    }
};

worker.RunWorkerAsync();

One improvement could be to combine datarec and rec_data as a Tuple in args.Result.

How to find the cause of a UI freeze?, Use a backgroundworker, put serialport_FT(0, 1) in DoWork() and put if (datarec) { How to avoid freezing of GUI? Ask Question Asked 7 years, 11 months ago. Active 7 years, 11 months ago. Viewed 15k times 3. 1. i have a code which is like this :

In the background worker you use the DoWork event.

worker.DoWork += new DoWorkEventHandler(yourEventHandler); 

void yourEventHandler(object sender, DoWorkEventArgs e)
{
//your work here
}

What are some methods to avoid GUI freezing? : csharp, cross thread exception do something like this: stackoverflow.com/a/1136406/400303 – Mohammad Jun 26 '12 at 8:22. Re:To avoid freezing GUI Windows timers, (around which TTimer is a wrapper), work by assembling a WM_TIMER message in the Windows message queue of *the thread that

As you are using WinForms, here is a great MSDN article to get you started with using multiple threads in an application: Give Your .NET-based Application a Fast and Responsive UI with Multiple Threads

The article is 'a few days old', but the principles remain absolutely valid today.

If you are working in a .NET 4.x version, you can also use the Task Parallel Library to make working with multiple threads easier.

The upcoming .NET 4.5 also offers the even more comfortable await and asyc keywords: Asynchronous Programming with Async and Await.

GUI help! TKInter keeps freezing when button is pressed : learnpython, In this screencast, we will analyze a user interface (UI) freeze in a Windows Presentation Duration: 4:34 Posted: Apr 8, 2019 3. Java GUI, need to pause a method without freezing GUI aswell stackoverflow.com. I know that this problem is caused by the sleep or wait calling on the main thread and that the answer on how to solve this will be to put the

Put this in a background thread as you already tried (or better yet, a Task), but be careful to call GUI-related operations only through Control.Invoke (for WinForms) or Dispatcher.Invoke (for WPF).

5 Things to do when your Linux system GUI freezes, I have done some WinForms applications and those which require using a timer and checking the list and doing math operations with the list makes the GUI� This is my first graphic user interface attempt so bear with me. I am trying to write a simple GUI that just stores the entered values when the button is pressed. It works, but I am only able to press the button once, because the GUI freezes completely as soon as its hit. I'm using Pycharm as my IDE and my code is pretty straight forward.

Used a Label which updates in real time as the task progresses. You can try this code [using BackGroundWorker]. Look at DoWork where you put your business logic [See BusinessClass usage in the code], then see the ProgressChanged where the background task signals the UI in real time as the task progresses & finally see the RunWorkerCompleted where you handle code after task completion, error or cancellation.

using System.ComponentModel;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form3 : Form
    {
        private BackgroundWorker _worker;
        BusinessClass _biz = new BusinessClass();
        public Form3()
        {
            InitializeComponent();
            InitWorker();
        }

        private void InitWorker()
        {
            if (_worker != null)
            {
                _worker.Dispose();
            }

            _worker = new BackgroundWorker
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };
            _worker.DoWork += DoWork;
            _worker.RunWorkerCompleted += RunWorkerCompleted;
            _worker.ProgressChanged += ProgressChanged;
            _worker.RunWorkerAsync();
        }


        void DoWork(object sender, DoWorkEventArgs e)
        {
            int highestPercentageReached = 0;
            if (_worker.CancellationPending)
            {
                e.Cancel = true;
            }
            else
            {
                double i = 0.0d;
                int junk = 0;
                for (i = 0; i <= 199990000; i++)
                {
                    int result = _biz.MyFunction(junk);
                    junk++;

                    // Report progress as a percentage of the total task.
                    var percentComplete = (int)(i / 199990000 * 100);
                    if (percentComplete > highestPercentageReached)
                    {
                        highestPercentageReached = percentComplete;
                        // note I can pass the business class result also and display the same in the LABEL  
                        _worker.ReportProgress(percentComplete, result);
                        _worker.CancelAsync();
                    }
                }

            }
        }

        void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                // Display some message to the user that task has been
                // cancelled
            }
            else if (e.Error != null)
            {
                // Do something with the error
            }
        }

        void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            label1.Text =  string.Format("Result {0}: Percent {1}",e.UserState, e.ProgressPercentage);
        }
    }

    public class BusinessClass
    {
        public int MyFunction(int input)
        {
            return input+10;
        }
    }
}

Find the Cause of a UI Freeze - Help, This is my first graphic user interface attempt so bear with me. I am trying to write a simple GUI that just stores the entered values when the … QT MYSQL GUI Avoid GUI freezing by using QThread Example I have example application 3 header file 4 cpp file 1 gui file. I want you to edit code that when i add entry GUI won't freeze. Use QThread but don't sub class it just move to thread. And don't leave memory leak after process. You will need web server or xampp local server.

[Solved] Preventing UI freeze on windows form., This method is applicable in situations where your GUI has frozen, but running on the terminal, the easiest way would press Ctrl + C to stop it. everything works fine and my GUI does not freeze. But when i call BeginInvoke to set my generated Report in the Report Viewer the whole GUI freezes for about 6 seconds. How can i avoid freezing my gui? Thanks in advance, manu

Tkinter GUI freeze, dotTrace tutorial, .NET C# performance profiling tutorial, .NET UI freezes, UI performance, .NET performance profiler, WPF performance,� Generally speaking, it’s best to avoid thawing food at room temperature, especially meat, poultry and fish, as this can pose an elevated risk for contamination. Instead, allow frozen foods to thaw in the refrigerator—in the case of meats and poultry, a good rule of thumb is about 1 hour per pound.

Freeze � Thread � Java Swing Q&A, How I usually approach this type of problem is to either spawn a new thread[^] or use the ThreadPool.QueueUserWorkItem method to use a� Keep the UI thread responsive. 02/08/2017; 4 minutes to read +4; In this article. Users expect an app to remain responsive while it does computation, regardless of the type of machine.

Comments
  • Put the call to serialport_FT() in a background thread - see stackoverflow.com/search?q=c%23+gui+background
  • Use a backgroundworker, put serialport_FT(0, 1) in DoWork() and put if (datarec) { ... } inside the Completed() event.
  • In order to avoid cross thread exception do something like this: stackoverflow.com/a/1136406/400303
  • thank you for the reply going through all those docs
  • thank you...tried this... i did not get any error this time but the UI din get updtated. I put the block: if(datatarec){...} under if(result){...}. What am i doing wrong?
  • Did you check that serialport_FT returned true and that result is true?
  • yes result is true... so after that i call another function which has lines under if(datarec){...} [in question post] ovalShapesX[1-6] aren't updating neither giving me exceptions nor errors
  • Hmm... And the data looks ok I pressume? Did the UI stuff work before? Is the text field updated?
  • data is ok ,used toolStripStatusLabel1.Text = "tested"; after the function is done calling, which is displayed. the code which i have posted above is a working 1 except for a small freeze point in while executing datarec= serial_FT(0,1); so i wanted to use background worker now
  • i don get it ... can u please be little more elaborate?