mercredi 8 juillet 2020

why IProcess

I want to use IProcess to report the running status of background task. it can work at Console application, but failed w/ Winform application. I used .net framework 4.6.1, compiled to x64

The Test main is

public class MyTestInvoke
{
    public MyTestInvoke() {}

        public void Run()
        {
            var progress = new Progress<int>(handler_ProgressChanged);

            Type theTest = typeof(MyTest);
            ConstructorInfo theConstructor = theTest .GetConstructor(Type.EmptyTypes);
            object theClassObject = theConstructor.Invoke(new object[] { });

            MethodInfo theMethod = theTest.GetMethod("RunProcess");

            try
            {
                theMethod.Invoke(theClassObject, new object[] { progress });
            }
            catch (Exception ex)
            {
                
            }
        }

        private void handler_ProgressChanged(int returnVal)
        {
            Console.WriteLine("MyTestInvoke::handler_ProgressChanged,thread Id is: {0}, returnVal={1}", Thread.CurrentThread.ManagedThreadId, returnVal);
        }
}

The following code is MyTest

public class MyTest
{
    int sleep = 1;

    public MyTest()
    {

    }

    public void RunProcess(IProgress<int> progress)
    {
        for (int i = 0; i < 4; i++)
        {
            progress.Report(i);
            System.Threading.Thread.Sleep(300);
        }
    }
}

when run at WinForm, just call MyTestInvoke by button event

private void btnTest_Click(object sender, EventArgs e)
{
    this.btnTest.Enabled = false;

    MyTestInvoke mi = new MyTestInvoke();
    mi.Run();
}

Also at Console app, just call the same class the same way,

[STAThread]
static void Main(string[] args)
{
    MyTestInvoke mt = new MyTestInvoke();
    mt.Run();
    Console.ReadLine();
}

When run as console app, the progress handler will be called every loop, but run as Winform, the progress handler will only be activated after RunProcess finished. Even I added an "async Task" to the RunProcess function, both run w/ the same results.

What the difference for both?





Aucun commentaire:

Enregistrer un commentaire