C#InvokeRequired与属性获取器 [英] C# InvokeRequired with property getter

查看:365
本文介绍了C#InvokeRequired与属性获取器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保我的吸气剂线程安全.当我这样做时,我得到一个错误:

I would like to make my getter thread safe. When I do this, I get an error:

public ApplicationViewModel SelectedApplication
    {
        get
        {
            if (InvokeRequired)
            {
                BeginInvoke((Action<ApplicationViewModel>)SelectedApplication);
            }

            return _applicationsCombobox.SelectedItem as ApplicationViewModel;
        }
    }

我有错误:

Cannot cast expression of type 'Foo.Model.ApplicationViewModel' to type 'Action<ApplicationViewModel>'

推荐答案

很多错误:

  • 您不能使用BeginInvoke, Invoke 是必需的
  • 您无法使用Action<>,您正在返回一个值,因此需要 Func<>
  • 您也不能在调用后运行原始代码,需要 else .

哪个会产生:

public ApplicationViewModel SelectedApplication
{
    get
    {
        if (this.InvokeRequired)
            return (ApplicationViewModel)this.Invoke(new Func<ApplicationViewModel>(() => this.SelectedApplication));
        else
            return _applicationsCombobox.SelectedItem as ApplicationViewModel;
    }
}

将线程上下文开关隐藏在低级属性中通常是一个错误.调用会产生很多开销,最终的代码可能会变得非常慢,而没有很好的提示为什么这么慢.

Hiding the thread context switches in a low-level property is usually a mistake. Invoking has lots of overhead, the resulting code may end up being very slow without a good hint of why it is so slow.

这篇关于C#InvokeRequired与属性获取器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆