12

我目前正在尝试编写一个组件,它的某些部分应该在 UI 线程上运行(解释会很长)。因此,最简单的方法是将控件传递给它,并在其上使用 InvokeRequired/Invoke。但我认为将控件引用传递给“数据/背景”组件不是一个好的设计,所以我正在寻找一种在 UI 线程上运行代码而不需要可用控件的方法. WPF中的Application.Dispatcher.Invoke之类的...

任何想法,谢谢马丁

4

5 回答 5

19

有一种更好、更抽象的方法可以在 WinForms 和 WPF 上运行:

System.Threading.SynchronizationContext.Current.Post(theMethod, state);

这是因为 WindowsForms 安装了一个WindowsFormsSynchronizationContext对象作为当前同步上下文。WPF 做了类似的事情,安装它自己的专用同步上下文 ( DispatcherSynchronizationContext)。

.Post对应control.BeginInvoke,.Send对应control.Invoke.

于 2009-02-02T23:03:32.987 回答
3

首先,在您的表单构造函数中,保留对对象的类范围引用SynchronizationContext.Current(实际上是 a WindowsFormsSynchronizationContext)。

public partial class MyForm : Form {
    private SynchronizationContext syncContext;
    public MyForm() {
        this.syncContext = SynchronizationContext.Current;
    }
}

然后,在您班级的任何地方,使用此上下文向 UI 发送消息:

public partial class MyForm : Form {
    public void DoStuff() {
        ThreadPool.QueueUserWorkItem(_ => {
            // worker thread starts
            // invoke UI from here
            this.syncContext.Send(() =>
                this.myButton.Text = "Updated from worker thread");
            // continue background work
            this.syncContext.Send(() => {
                this.myText1.Text = "Updated from worker thread";
                this.myText2.Text = "Updated from worker thread";
            });
            // continue background work
        });
    }
}

您将需要以下扩展方法来使用 lambda 表达式:http ://codepaste.net/zje4k6

于 2012-02-24T15:18:14.533 回答
2

你是对的,将控件传递给线程是不好的。Winforms 控件是单线程的,将它们传递给多个线程可能会导致竞争条件或破坏您的 UI。相反,您应该将线程的功能提供给 UI,并在 UI 良好且准备就绪时让它调用线程。如果您想让后台线程触发 UI 更改,请公开一个后台事件并从 UI 订阅它。线程可以随时触发事件,并且 UI 可以在可能时响应它们。

在不阻塞 UI 线程的线程之间创建这种双向通信需要大量工作。这是一个使用 BackgroundWorker 类的高度缩写示例:

public class MyBackgroundThread : BackgroundWorker
{
    public event EventHandler<ClassToPassToUI> IWantTheUIToDoSomething;

    public MyStatus TheUIWantsToKnowThis { get { whatever... } }

    public void TheUIWantsMeToDoSomething()
    {
        // Do something...
    }

    protected override void OnDoWork(DoWorkEventArgs e)
    {
        // This is called when the thread is started
        while (!CancellationPending)
        {
            // The UI will set IWantTheUIToDoSomething when it is ready to do things.
            if ((IWantTheUIToDoSomething != null) && IHaveUIData())
                IWantTheUIToDoSomething( this, new ClassToPassToUI(uiData) );
        }
    }
}


public partial class MyUIClass : Form
{
    MyBackgroundThread backgroundThread;

    delegate void ChangeUICallback(object sender, ClassToPassToUI uiData);

    ...

    public MyUIClass
    {
        backgroundThread = new MyBackgroundThread();

        // Do this when you're ready for requests from background threads:
        backgroundThread.IWantTheUIToDoSomething += new EventHandler<ClassToPassToUI>(SomeoneWantsToChangeTheUI);

        // This will run MyBackgroundThread.OnDoWork in a background thread:
        backgroundThread.RunWorkerAsync();
    }


    private void UserClickedAButtonOrSomething(object sender, EventArgs e)
    {
        // Really this should be done in the background thread,
        // it is here as an example of calling a background task from the UI.
        if (backgroundThread.TheUIWantsToKnowThis == MyStatus.ThreadIsInAStateToHandleUserRequests)
            backgroundThread.TheUIWantsMeToDoSomething();

        // The UI can change the UI as well, this will not need marshalling.
        SomeoneWantsToChangeTheUI( this, new ClassToPassToUI(localData) );
    }

    void SomeoneWantsToChangeTheUI(object sender, ClassToPassToUI uiData)
    {
        if (InvokeRequired)
        {
            // A background thread wants to change the UI.
            if (iAmInAStateWhereTheUICanBeChanged)
            {
                var callback = new ChangeUICallback(SomeoneWantsToChangeTheUI);
                Invoke(callback, new object[] { sender, uiData });
            }
        }
        else
        {
            // This is on the UI thread, either because it was called from the UI or was marshalled.
            ChangeTheUI(uiData)
        }
    }
}
于 2009-01-20T20:08:57.290 回答
1

传递 System.ComponentModel.ISynchronizeInvoke 怎么样?这样你就可以避免传递一个控件。

于 2009-02-02T18:52:55.427 回答
1

将 UI 操作放在要操作的表单上的方法中,并将委托传递给在后台线程上运行的代码,à la APM。您不必使用params object p,您可以强烈键入它以适合您自己的目的。这只是一个简单的通用示例。

delegate UiSafeCall(delegate d, params object p);
void SomeUiSafeCall(delegate d, params object p)
{
  if (InvokeRequired) 
    BeginInvoke(d,p);        
  else
  {
    //do stuff to UI
  }
}

这种方法基于委托引用特定实例上的方法这一事实。通过使实现成为表单的方法,您可以将表单作为this. 以下在语义上是相同的。

delegate UiSafeCall(delegate d, params object p);
void SomeUiSafeCall(delegate d, params object p)
{
  if (this.InvokeRequired) 
    this.BeginInvoke(d,p);        
  else
  {
    //do stuff to UI
  }
}
于 2009-01-28T05:06:24.917 回答