Don't raise TextChanged while continuous typing

后端 未结 12 1257
闹比i
闹比i 2020-12-14 10:09

I have a textbox that has a fairly hefty _TextChanged event handler. Under normal typing condition the performance is okay, but it can noticeably lag when the u

12条回答
  •  温柔的废话
    2020-12-14 10:29

    You can mark your event handler as async and do the following:

    bool isBusyProcessing = false;
    
    private async void textBox1_TextChanged(object sender, EventArgs e)
    {
        while (isBusyProcessing)
            await Task.Delay(50);
    
        try
        {
            isBusyProcessing = true;
            await Task.Run(() =>
            {
                // Do your intensive work in a Task so your UI doesn't hang
            });
    
        }
        finally
        {
            isBusyProcessing = false;
        }
    }
    

    Try try-finally clause is mandatory to ensure that isBusyProcessing is guaranted to be set to false at some point, so that you don't end up in an infinite loop.

提交回复
热议问题