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

时间:2017-10-29 00:16:14

标签: c# wpf multithreading

我的主窗口代码中有一个定时器设置,每十秒触发一次。因为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();
        });
    }

1 个答案:

答案 0 :(得分:3)

将您的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());
}