posts - 930,  comments - 588,  views - 402万
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8
      在WinForm中的多线程中,操作控件时,会报无效操作异常,解决方法是调用System.Windows.Form.Control中BeginInvoke。
代码如下:
Code

再看《CLR.via.C#.Second.Edition.Feb.2006》中是这么说,这下清楚了。
 
  
 In Windows, a window is always created by a thread, and this thread must be used to process
all actions for the window. One reason for this is because  16-bit Windows versions were sin-
gle-threaded operating systems, and in order to maintain backward compatibility, 32-bit and 64-
bit versions of Windows kept the single-threaded architecture for handling window opera-
tions such as WM_MOVE, WM_SIZE, WM_PAINT,  WM_CLOSE, etc. It's common for a Windows Forms
application to use the asynchronous techniques explained in this chapter. However, since Win-
dows Forms is built on top of Windows, a thread pool thread is not allowed to directly manipu-
late a window; or more specifically, a class derived from System.Windows.Forms.Control.

    Fortunately, the System.Windows.Forms.Control class offers three methods—Invoke, Begin-
Invoke
, and EndInvoke-that you can call from any thread (including a thread pool thread) to
marshal an operation from the calling thread to the thread that created the window. Inter-
nally, Control's Invoke method calls the Win32 SendMessage method to have the window's
thread execute a task synchronously. Control's BeginInvoke method internally calls the
Win32 PostMessage method to have the window's thread execute a task asynchronously. If
the calling thread wants to know when the window's thread has completed executing the
task, it can call Control's EndInvoke method. If you don't care, this is one of the rare cases
when you do not have to call an EndInvoke method.


posted on   PetterLiu  阅读(1390)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
点击右上角即可分享
微信分享提示