Strange cross-threading UI errors

好久不见. 提交于 2019-12-04 06:33:40

Since you are doing UI binding via event subscription, you might find this helpful; it is an example I wrote a while ago that shows how to subclass BindingList<T> so that the notifications are marshalled to the UI thread automatically.

If there is no sync-context (i.e. console mode), then it reverts back to the simple direct invoke, so there is no overhead. When running in UI thread, note that this essentially uses Control.Invoke, which itself just runs the delegate directly if it is on the UI thread. So there is only any switch if the data is being edited from a non-UI thread - juts what we want ;-p

Skizz

You've answered your own quesion:-

I get an error saying that the DataGridView was being accessed from a thread other than the thread it was created on.

WinForms insists that all actions performed on forms and controls are done in the context of the thread the form was created in. The reason for this is complex, but has a lot to do with the underlying Win32 API. For details, see the various entries on The Old New Thing blog.

What you need to do is use the InvokeRequired and Invoke methods to ensure that the controls are always accessed from the same thread (pseudocodeish):

object Form.SomeFunction (args)
{
  if (InvokeRequired)
  {
    return Invoke (new delegate (Form.Somefunction), args);
  }
  else
  {
    return result_of_some_action;
  }
}

I had this same problem before. Maybe this article I posted about it can help.

http://cyberkruz.vox.com/library/post/net-problem-async-and-windows-forms.html

I found this article - "Updating IBindingList from different thread" - which pointed the finger of blame to the BindingList -

Because the BindingList is not setup for async operations, you must update the BindingList from the same thread that it was controlled on.

Explicitly passing the parent form as an ISynchronizeInvoke object and creating a wrapper for the BindingList<T> did the trick.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!