简体   繁体   English

c + + cli c#winforms跨线程操作有时可能

[英]c++/cli c# winforms cross-thread operation sometimes possible

I am using c++/cli (should also apply to c#) and creating a winforms program. 我正在使用c ++ / cli(也应适用于c#)并创建一个winforms程序。

I have some lines of code that edit data in a DataGridView. 我有一些代码行可以编辑DataGridView中的数据。 The code is executed by an FileSystemWatcher event, but it could be executed by a background worker or a simple thread. 该代码由FileSystemWatcher事件执行,但可以由后台工作程序或简单线程执行。 However, it is NOT executed by the UI thread. 但是,它不是由UI线程执行的。
The DGV is placed on a tab of a TabControl. DGV放置在TabControl的选项卡上。 When the code is executed while the DGV-containing tab has the focus, the code fails with the well-known and expected exception " Cross-thread operation not valid ". 当在包含DGV的选项卡具有焦点的情况下执行代码时,代码将失败,并带有众所周知的预期异常“ 跨线程操作无效 ”。

But when another tab has the focus, the code executes smoothly. 但是当另一个选项卡具有焦点时,代码将顺利执行。 I assume that the DGV is not updated when it's not shown, causing the code to work well in this case. 我假设DGV在未显示时未更新,因此在这种情况下代码可以正常工作。 But this means that the sending of messages like WM_PAINT to the message queue depends on the visibility (shown or not) of the DGV, and in case it is not visible, those messages must be sent when the DGV gets shown again. 但这意味着将诸如WM_PAINT之类的消息发送到消息队列取决于DGV的可见性(是否显示),并且在不可见的情况下,必须在再次显示DGV时发送这些消息。

Is this correct? 这个对吗?
What are the differences in code exection when the DGV is (not) shown? 未显示DGV时,代码执行有什么区别?

Your code is fundamentally wrong, but that does not mean that you are guaranteed to be reminded about it. 您的代码从根本上是错误的,但这并不意味着可以保证您会被提醒。 It won't bomb when the control is not visible, no need to update it so no need to do anything that's thread-unsafe so no exception. 当控件不可见时,它不会炸弹,不需要更新它,因此不需要执行任何线程不安全的操作,因此也不例外。

You must fix the underlying problem. 必须解决基本问题。 Very easy to do with the FileSystemWatcher::SynchronizingObject property. 使用FileSystemWatcher :: SynchronizingObject属性非常容易。 Just set it to this in the form constructor. 只需在表单构造函数中将其设置为此 Now the event is automatically raised on the UI thread and you can party on the control properties without being rapped on the knuckles. 现在,该事件将在UI线程上自动引发,您可以加入控件属性,而不必费劲。 Fix: 固定:

    MyForm(void)
    {
        InitializeComponent();
        fileSystemWatcher1->SynchronizingObject = this;
    }

With the assumption that you dropped the FSW from the toolbox onto your form. 假设您将FSW从工具箱拖放到了表单上。 Tweak as needed. 根据需要进行调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM