0

我有许多从后台线程调用的函数,但随后需要执行 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
}

我遇到的主要问题是必须在上下文切换中明确提及我自己的函数名称(我部分不喜欢这个,因为我在复制和粘贴代码时总是忘记更改名称!)

关于切换上下文的更通用方式的任何想法,例如,是否有任何方法可以通过一些避免显式命名函数的巧妙指针回调我自己的函数?

像这个片段这样的东西会很好(但是它不会构建):

    this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => this(test))); return; 

想法?

4

2 回答 2

2

将调度代码拉到一个单独的方法中怎么样?

public void Dispatch(Action action)
{
    if (!this.Dispatcher.CheckAccess()) 
    {
        this.Dispatcher.Invoke(DispatcherPriority.Normal, action);
    }
    else
    {
        action();
    }
}

和:

Dispatch(() => FunctionABC(test));
于 2012-07-04T10:45:42.047 回答
2

您可以采用这种可重用的方法:

private void ExecuteOnDispatcherThread(Action action)
{
    if (!this.Dispatcher.CheckAccess()) {
        this.Dispatcher.Invoke(DispatcherPriority.Normal, action); 
    }
    else {
        action();
    }
}

并像这样调用它:

this.ExecuteOnDispatcherThread(() => FunctionABC(test));
于 2012-07-04T10:45:47.090 回答