【发布时间】:2012-07-04 10:38:05
【问题描述】:
我有许多从后台线程调用的函数,但随后需要执行 GUI 操作。因此,在每个函数中,我将上下文切换到 GUI 线程。但是我想知道我的代码是否可以改进?
下面是我的代码现在通常看起来的简化示例:
public void FunctionABC(string test)
{
// Make sure we are in the GUI thread.
if (!this.Dispatcher.CheckAccess())
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => FunctionABC(test))); return;
}
// main body of function
}
我遇到的主要问题是必须在上下文切换中明确提及我自己的函数名称(我部分不喜欢这个,因为我在复制和粘贴代码时总是忘记更改名称!)
关于更通用的上下文切换方式的任何想法,例如有什么方法可以通过一些避免显式命名函数的巧妙指针回调我自己的函数?
像这样的 sn-p 会很好(但它不会构建):
this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => this(test))); return;
想法?
【问题讨论】:
标签: c# multithreading invoke