为什么我的异步计时器阻止了 UI 线程



我在后面的主窗口代码中设置了一个计时器,每十秒触发一次。由于 timer_Elapsed 事件中引用的某些代码有些占用 CPU 资源,因此我将其放置在await Task.Run(() =>中,但是每当经过的事件运行时,UI 线程都会继续暂时挂起。任何想法为什么这会阻止 UI?法典:

async void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        await Task.Run(() =>
        {
            //Update default status bar text routinely
            try
            {
                if (ChecEnabled())
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        StatusText.Text = String.Format("Status: Enabled. Watching for changes…");
                    });
                }
                else
                {
                    this.Dispatcher.Invoke(() =>
                    {
                        StatusText.Text = String.Format("Status: Disabled");
                    });
                }
            }
            catch (ObjectDisposedException)
            {
                //Window closed and disposed timer on different thread
            }
            //System Checks
            UpdateSystemReadyStatus();
        });
    }

Invoke更新为 InvokeAsync 。另外,你真的需要将整个方法包裹在Task中吗?

async void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
    //Update default status bar text routinely
    try
    {
        if (ChecEnabled())
        {
            await this.Dispatcher.InvokeAsync(() =>
            {
                StatusText.Text = String.Format("Status: Enabled. Watching for changes…");
            });
        }
        else
        {
            await this.Dispatcher.InvokeAsync(() =>
            {
                StatusText.Text = String.Format("Status: Disabled");
            });
        }
    }
    catch (ObjectDisposedException)
    {
        //Window closed and disposed timer on different thread
    }
    //System Checks
    await Task.Run(()=>UpdateSystemReadyStatus());
}

最新更新