-3

I have a function which makes process. At the beginning of the function I want to change the text of a label which indicates the state, and once the process ends, change it again.

The fact is that only is shown the final change.

I know I can make a thread for the process but not needed in this case and I merely want to know if there's some tip or trick to accomplish it whitout the use of a thread.

Apalabrados
  • 1,098
  • 8
  • 21
  • 38
  • any code will be helpful? I am not sure are you taking about web or desktop or windows apps – Jayakrishnan Jun 10 '17 at 16:30
  • This label just has to change two times? One at the beginning and one at the end? Just change it in the calling method, right before the processing function – Davide Vitali Jun 10 '17 at 16:32
  • 1
    There are several options that don't involve "threads" such as async/await, BackgroundWorker, etc. But one way or another you're going to have to get the processing off the UI thread to keep it from blocking the UI. – BJ Myers Jun 10 '17 at 16:40
  • See also https://stackoverflow.com/questions/25152207/how-do-i-use-await-async-with-synchronous-code – Peter Duniho Jun 10 '17 at 16:54

1 Answers1

-1

In this case When you change something in UI it does not change until the whole process is completed so as you said you can only see the final state of your label. The trick is simple. You need to use a secondary thread while you are going to update the label for the fist time. Look at the example below :

 class Program
    {
        private delegate void del();
        static void Main(string[] args)
        {
            del d = updateConsole;
            var res = d.BeginInvoke(null, null);
            while (!res.IsCompleted)
            {
                // do the job here
            }
            d.EndInvoke(res);
            Thread.Sleep(1000);
            Console.Clear();
            Console.WriteLine("Done!");
            Console.Read();
        }

        private static void updateConsole()
        {
            for (var i = 0; i <= 10; i++)
            {
                Thread.Sleep(500);
                Console.Clear();
                Console.WriteLine(i);
            }

        }
    }

This simple technique helps you to separate the first update of the label from the whole process.

Mahmood Shahrokni
  • 226
  • 1
  • 3
  • 12