Link to home
Start Free TrialLog in
Avatar of Skale
Skale

asked on

Prompting user while assigning a value with function in C#

I've very simple code which assigns a COM type object to global variable named Global.MDL with below code.

        private bool OpenSimpackModel(String filename)
        {
            try
            {
                Globals.MDL = Globals.APP.Spck.openModel(filename);
                if (Globals.MDL != null)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
                throw;
            }

        }

Open in new window


But while it's trying to assigns it tookes some time and locks my gui controls, at least i'd like to show loading bar until this process completed otherwise user don't know what is causing that.

How is it possible to show loading bar when application start to call  below function.

             Globals.MDL = Globals.APP.Spck.openModel(filename);

Open in new window


Any help would be grateful.

Thank you.
Avatar of fcnatra
fcnatra
Flag of Spain image

The following sample will run the task asynchronously, so it will let you trigger the COM operation in a different execution thread and continue with the rest of the operations.

The idea is just to show the user some feedback (busy icon or so) - so on this code I propose you to use a "while" loop to wait for the end of the task and update the UI feedback every other second.

Instead of calling "OpenSimpackModel" function, try calling the "OpenSimpackModelAsync" version, wich reuse your current function and provides feedback.

private bool OpenSimpackModelAsync(String fileName)
{
	bool result = false;
	var task = new Task(() =>
	{
		result = OpenSimpackModel(fileName);
	});
	task.Start();

	while (!task.IsCompleted)
	{
		Thread.Sleep(1000);
		Console.WriteLine($"task is running... {DateTime.Now.TimeOfDay.ToString()}"); // On WinForms you might need to use Application.DoEvents();
	}

	return result;
}

Open in new window

Avatar of Skale
Skale

ASKER

How we can apply this if it's type of void. Because if we want to assign void method to result it will give an error because it's bool and cannot convert to void.

            result = OpenSimpackModel(fileName);
ASKER CERTIFIED SOLUTION
Avatar of fcnatra
fcnatra
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial