Home > Mobile >  Is this the correct way to use the invoke function?
Is this the correct way to use the invoke function?

Time:08-30

I want to constantly refresh my form to update the information displayed on the form. and do not want the program to crash. When I looked for answers on the Internet, when I got an answer that I had to use a function "Control.Invoke". After that I wrote this code`

    private void Form1_Load(object sender, EventArgs e)
    {
            Thread Data = new Thread(RefreshData) { IsBackground = true };
            Data.Start();
    }


    void RefreshData()
    {
        while (true)
        {
            //...rewrite all data display on form
            this.Invoke((MethodInvoker)delegate { this.Refresh(); });
            Thread.Sleep(33);
        }
    }

Is this the correct way to use the invoke function?

CodePudding user response:

Yes, you can use Invoke that way, however I would advise you to avoid creating threads manually.

Instead, use the newer async and Task.Run features. You can also write the anonymoous lambda using a shorter syntax, although it comes to the same thing.

private void Form1_Load(object sender, EventArgs e)
{
    Task.Run(RefreshData);
}

async Task RefreshData()
{
    while (!this.IsDisposed)
    {
        // await stuff here??
        //...rewrite all data display on form
        this.Invoke((MethodInvoker)() => this.Refresh());
        await Task.Delay(33);
    }
}

Another alternative is to allow the task scheduler to marshal the continuation back to the UI thread. This means that no calls to UI functions can happen inside of the function called by Task.Run

private void Form1_Load(object sender, EventArgs e)
{
    Task.Run(RefreshData);
}

async void RefreshData()
{
    while (!this.IsDisposed)
    {
        await Task.Run(RefreshDataInternal);
        this.Refresh();
        await Task.Delay(33);
    }
}

async Task RefreshData()
{
    // await stuff here
    // Do NOT call the UI
}
  • Related