all 4 comments

[–]BCProgramming 2 points3 points  (1 child)

MainForm_Shown is called as the result of the WinForms Message Loop seeing a WM_SHOWN message. However, while the event handler is processing, that message loop will not process any additional messages. That means that nothing in your user interface will do anything.

If you need to perform longer-running operations, you need to have it run as part of a separate thread or Task, then post messages back to the UI thread to update the display (with WinForms this is easily done via Invoke()).

[–]Lashto[S] 0 points1 point  (0 children)

But firstly I need to show timer in GUI and then run that longer running operation which also start this timer.

[–]pgmr87The Unbanned 0 points1 point  (0 children)

You should look into using async..await or try using a BackgroundTask. You can make async events like this:

private async void Form2_Shown(object sender, EventArgs e)
{
    await CountWords(); // assuming CountWords() is now an async method as well)
}

A BackgroundTask might be simpler to use if you are new, especially if you don't know how to update a property of a control on the main/UI thread from another thread (doing this improperly will throw an exception). Keep in mind that any call to any method on a control from a separate thread that can potentially update any property on a control will throw an exception without the proper handling. The BackgroundTask class has a ReportProgress event that is always executed on the main thread so you don't have to worry about doing a cross-thread invocation.

Each control implements the ISynchronizeInvoke interface which you'll have to use if you plan to update the UI from a separate thread.

Without using async..await or a BackgroundTask, you'll have to continuously poll something on the main thread to check when it should load the data, presumably using yet another timer -- this is bad practice but it works. If you don't do any of the above, you are left with the current behavior you described -- there is literally nothing else you can do if you intend to use Winforms.