您的位置:首页 > 其它

多线程BUG捕捉之:由于其他线程拥有此对象,因此调用线程无法对其进行访问

2010-03-16 18:09 886 查看
以下论述只适用于WPF和WCF场合。

在进行WCF通信的时候,有时候会出现“由于其他线程拥有此对象,因此调用线程无法对其进行访问”。如下面的这段代码就可能会出现这个错误:

EndpointAddress tcpAddress = new EndpointAddress(new Uri(_wcfServiceUri), identity, headers);
_duplexChannelFactory = new DuplexChannelFactory<IStudentPcService>(
new InstanceContext(new CallStudentPcBack()), tcpBinding, tcpAddress);

经过调试发现,_wcfServiceUri出现了问题。经查,如果此处直接指定地址,无问题,可是换成了_wcfServiceUri这个变量就有问题了。追溯到_wcfServiceUri这个变量,发现该变量为了让WPF页面可以动态更新,为一个DependencyProperty,即:

public static readonly DependencyProperty StudentIpProperty =
DependencyProperty.Register("StudentIp", typeof(string),
typeof(StudentInfo), new UIPropertyMetadata(null));
public string StudentPcIp
{
get { return (string)GetValue(StudentIpProperty); }
set { SetValue(StudentIpProperty, value); }
}

于是问题找到了,因为_wcfServiceUri也就是StudentPcIp,是DependencyProperty,也就是说,拥有它的线程是WPF即主UI线程,而WCF的通信操作在我的程序里是在一个线程池中,所以报错。将变量替换之,问题解决。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐