使用MethodInvoker无需调用 [英] Using MethodInvoker without Invoke
问题描述
我现在有一段时间了编写GUI应用程序,并有一件事我一直用的都是MethodInvoker + lambda函数做跨线程访问。
这是我发现的例子我总是看到这样的东西:
版本1
如果(InvokeRequired)
{
调用(新MethodInvoker(()=>
{
Label1.Text =Foobar的;
} );
}
,否则
{
Label1.Text =Foobar的;
}
然而,这导致代码的重复数据删除 - >大坏蛋给我
那么,有什么不对的? / p>
版本2
MethodInvoker UPDATETEXT =新MethodInvoker(()=>
{
Label1.Text =Foobar的;
});
如果(InvokeRequired)
$ { b $ b调用(UPDATETEXT);
}
,否则
{
UPDATETEXT();
}
现在我有功能的一个变量捆绑在适当的时候与调用或函数指针调用它。 2版的性能越差明智?或者是我不好的做法,使用匿名函数呢?
没有什么地方错了...但你可以添加一个扩展方法来让这一切有所更好:
公共静态无效InvokeIfNecessary(该控制的控制,
MethodInvoker动作)
{
如果(control.InvokeRequired)
{
control.Invoke(动作);
}
,否则
{
动作();
}
}
然后,你可以写:
this.InvokeIfNecessary(()=> Label1.Text =Foobar的);
更整洁:)
有一个的很轻微的从创建一个委托表现缺点时,你并不需要,但它几乎肯定微不足道的 - 专注于编写干净的代码
注意,即使你不想做,你仍然可以让你的变量声明简单在现有代码:
MethodInvoker UPDATETEXT =()=> Label1.Text =Foobar的;
这是一个使用独立的变量的一个好处 - 你不需要新MethodInvoker
位告诉lambda表达式是什么类型的委托你想...
的
I am writing GUI applications for some time now and one thing I always use are MethodInvoker + lambda functions to do cross-thread access.
From the examples I find I always see stuff like this:
Version 1
if (InvokeRequired)
{
Invoke(new MethodInvoker(() =>
{
Label1.Text = "Foobar";
});
}
else
{
Label1.Text = "Foobar";
}
However this leads to code-duplication --> major baddie to me.
So what's wrong with this?
Version 2
MethodInvoker updateText = new MethodInvoker(() =>
{
Label1.Text = "Foobar";
});
if (InvokeRequired)
{
Invoke(updateText);
}
else
{
updateText();
}
Now I have the functionality bundled in one variable and call it with Invoke or as a function pointer when appropriate. Is version 2 worse performance-wise? Or is i bad practice to use anonymous functions for this?
Nothing's wrong with it... but you can add an extension method to make it all somewhat nicer:
public static void InvokeIfNecessary(this Control control,
MethodInvoker action)
{
if (control.InvokeRequired)
{
control.Invoke(action);
}
else
{
action();
}
}
Then you can write:
this.InvokeIfNecessary(() => Label1.Text = "Foobar");
Much neater :)
There is a very slight performance drawback from creating a delegate when you don't need to, but it's almost certainly insignificant - concentrate on writing clean code.
Note that even if you don't want to do that, you can still make your variable declaration simpler in your existing code:
MethodInvoker updateText = () => Label1.Text = "Foobar";
That's one benefit of using a separate variable - you don't need the new MethodInvoker
bit to tell the lambda expression what type of delegate you want...
这篇关于使用MethodInvoker无需调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!