在没有控制对象存在的UI线程上运行代码

时间:2009-01-19 10:57:49

标签: winforms invoke ui-thread invokerequired

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

任何想法, 谢谢 马丁

5 个答案:

答案 0 :(得分:19)

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

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

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

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

答案 1 :(得分: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)
        }
    }
}

答案 2 :(得分:2)

首先,在表单构造函数中,保持对SynchronizationContext.Current对象(实际上是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

答案 3 :(得分:1)

将UI操作放在要操作的表单上的方法中,并将委托传递给在后台线程上运行的代码,即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
  }
}

答案 4 :(得分:1)

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