的WinForms - 什么是更新线程安全的方式财产的最简单方法 [英] Winforms - what is the simplest way to update a property in thread safe manner

查看:118
本文介绍了的WinForms - 什么是更新线程安全的方式财产的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我一直在使用设置在一个线程安全的方式(属性改编自的这个其他SO质疑,但我无法适应它获取属性。



这是线程安全的方式代码,我定的属性。

 公共静态无效SetPropertyThreadSafe(此的TControl自我,行动​​二传手)
式的TControl:控制
{
如果(self.InvokeRequired)
{
VAR调用=(动作)(()=>二传手(个体经营));
self.Invoke(调用者);
}
,否则
{
二传手(个体经营);
}
}

这是由执行以下称为:

  this.lblNameField.SetPropertyThreadSafe(p => p.Text =姓名:); 

这是我在线程安全的方式代码获取属性的尝试。

 公共静态TResult GetPropertyThreadSafe(此的TControl自我,Func键吸气)
式的TControl:控制
{
如果(self.InvokeRequired)
{
VAR调用=(Func键)((的TControl控制)=>吸气剂(个体经营));
回报(TResult)self.Invoke(调用者);
}
,否则
{
返回吸气剂(个体经营);
}
}



这是行不通的。我希望喜欢通过执行以下操作来调用它:

 字符串名称= this.lblNameField.GetPropertyThreadSafe(P => p.Text); 


解决方案

您应该能够使用:



 公共静态TResult GetPropertyThreadSafe<的TControl,TResult>(此的TControl自我,Func键<的TControl,TResult>吸气)
式的TControl:控制
{
如果(self.InvokeRequired)
{
回报(TResult)self.Invoke(吸气,个体经营);
}
,否则
{
返回吸气剂(个体经营);
}
}

您通过以下调用它:



  bool的可见= this.lblNameField.GetPropertyThreadSafe(p => p.Visible)


I have the following code that I have been using to Set properties in a thread safe manner (adapted from this other SO question, but I cannot adapt it to get the property.

This is my set property in thread safe way code.

public static void SetPropertyThreadSafe(this TControl self, Action setter)
    where TControl : Control
{
    if (self.InvokeRequired)
    {
        var invoker = (Action)(() => setter(self));
        self.Invoke(invoker);
    }
    else
    {
        setter(self);
    }
}

Which is called by doing the following:

this.lblNameField.SetPropertyThreadSafe(p => p.Text = "Name:");

This is my attempt at a get property in thread safe way code.

public static TResult GetPropertyThreadSafe(this TControl self, Func getter)
    where TControl : Control
{
    if (self.InvokeRequired)
    {
        var invoker = (Func)((TControl control) => getter(self));
        return (TResult)self.Invoke(invoker);
    }
    else
    {
        return getter(self);
    }
}

It doesn't work. I'd hopefully like to call it by doing the following:

string name = this.lblNameField.GetPropertyThreadSafe(p => p.Text);

解决方案

You should be able to use:

public static TResult GetPropertyThreadSafe<TControl, TResult>(this TControl self, Func<TControl, TResult> getter)
    where TControl: Control
{
    if (self.InvokeRequired)
    {
        return (TResult)self.Invoke(getter, self);
    }
    else
    {
        return getter(self);
    }
}

You call it by the following:

bool visible = this.lblNameField.GetPropertyThreadSafe(p => p.Visible)

这篇关于的WinForms - 什么是更新线程安全的方式财产的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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