调用线程无法访问此对象,因为另一个线程拥有该对象。一般来说可以这么做
在C#2005后不再支持多线程直接访问界面的控件(界面创建线程与访问线程不是同一个线程),但是可以可以使用delegate来解决。
次线程不能直接修改主线程UI的界面,需要使用以下方法
方法1:
[c-sharp]
view plain
copy
- this.Dispatcher.Invoke(DispatcherPriority.Normal,
- new Action(() =>
- {
- //调用主线程UI的的代码
- }));
还有一种是用delegte 的
btn.Dispatcher.Invoke(new Action(delegate { button1.Content = "some text"; }));
都可以,
但是我的问题是,一直都还是出错, 后来我才发现我的代码如下(只看高亮就好了)
try
{
_msgs
.
AddRange
(
tmpMsg
);
_latestSn
=
tmpMsg
.
Max
(one => one.
SN
);
Run txt ;
for
(
int
i
= 0 ;
i
<
tmpMsg
.
Count
(); ++
i
)
{
txt
=
new
Run
(
string
.
Format
(
"[{0}] {1}"
,
tmpMsg
[
i
].
sender
,
tmpMsg
[
i
] .
msgContent
));
txt
.
Foreground
=
Brushes
.
Wheat
;
this
.
Dispatcher
.
Invoke
(
DispatcherPriority
.
Normal
,
new
Action
(() =>
{
lblTest
.
Content
=
"ok"
;
this .textBlocKMsgs . Inlines. Add (txt );
this
.
textBlocKMsgs
.
Inlines
.
Add
(
new
LineBreak
());
}));
}
}
高亮的地方Run, 也是UI控件, 所以还是报错了, 把Invoke的范围放大一点,把Run的声明一起放进去就好了