Invoke 的潜在同步问题?
Potential sync issues with Invoke?
我正在尝试从工作线程中的控件中读取值。
public void worker()
{
while (true)
{
ewh.WaitOne();
int index = -1;
this.Invoke((MethodInvoker)delegate()
{
index = this.comboBoxSource.SelectedIndex;
});
// using index here
据我了解,Invoke 是异步启动的。在我使用 index
的地方不能保证 Invoke
会完成它的工作,我是对的吗?如果是这样,我怎样才能使 Invoke 成为阻塞操作?
As I understand Invoke is launched asynchronously.
不,Invoke
是同步的,因为它会阻塞,直到委托在 UI 线程中完成。不幸的是,Control.Invoke(Delegate)
. The other overload (Control.Invoke(Delegate, object[])
states that it's the implementation of ISynchronizeInvoke.Invoke
中没有明确记录这更清楚:
Unlike BeginInvoke
, this method operates synchronously, that is, it waits until the process completes before returning. Exceptions raised during the call are propagated back to the caller.
我正在尝试从工作线程中的控件中读取值。
public void worker()
{
while (true)
{
ewh.WaitOne();
int index = -1;
this.Invoke((MethodInvoker)delegate()
{
index = this.comboBoxSource.SelectedIndex;
});
// using index here
据我了解,Invoke 是异步启动的。在我使用 index
的地方不能保证 Invoke
会完成它的工作,我是对的吗?如果是这样,我怎样才能使 Invoke 成为阻塞操作?
As I understand Invoke is launched asynchronously.
不,Invoke
是同步的,因为它会阻塞,直到委托在 UI 线程中完成。不幸的是,Control.Invoke(Delegate)
. The other overload (Control.Invoke(Delegate, object[])
states that it's the implementation of ISynchronizeInvoke.Invoke
中没有明确记录这更清楚:
Unlike
BeginInvoke
, this method operates synchronously, that is, it waits until the process completes before returning. Exceptions raised during the call are propagated back to the caller.