admin 管理员组

文章数量: 1086019


2024年4月17日发(作者:on error resume next)

[WPF] 跨线程控制窗体UI

呼叫线程无法存取此对象

在WPF、WinForm这些应用程序中,必需是UI线程才能控制窗体。如果像是下列的范例程序一样,使用

了非UI线程来控制窗体,那就会看到内容为「呼叫线程无法存取此对象,因为此对象属于另外一个线程」

的InvalidOperationException例外错误。

?

1

xmlns="/winfx/2006/xaml/presentation"

2

xmlns:x="/winfx/2006/xaml"

3

Title="MainWindow" Height="350" Width="525">

4

5

6

?

1 namespace WpfApplication1

2 {

3 public partial class MainWindow : Window

4 {

5 // Fields

6 private readonly _timer =null;

7

8 private int _count = 0;

9

1

0 // Constructors

1 public MainWindow()

1 {

1 // Base

2 InitializeComponent();

1

3 // Timer

1 _timer =new (_Ticked,null, 0, 100);

4 }

1

5

1 // Handlers

6 private void Timer_Ticked(Object stateInfo)

1 {

7 _count++;

1 = _ng();

8 }

1 }

9 }

2

0

2

1


本文标签: 线程 窗体 控制