问题描述
我在主(GUI)线程中声明了一个对象,并从另一个线程实例化。我需要从中访问一个成员。但是访问该对象的方法会导致:
System.NullReferenceException:'对象引用未设置为对象的实例。'
srv为空。
以下是产生上述错误的代码:
I have an object declared in the main (GUI) thread and instantiated from another thread. I require to access a member from it. However accessing a method of the object results in:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
srv was null.
The following is the code resulting in the above error:
public partial class MainWindow : Window
{
Thread t = null;
ServerSpace.Server srv = null;
bool serveractive = false;
.
.
.
private void start_MouseDown(object sender, MouseButtonEventArgs e)
{
if(!serveractive)
{
App.connectioninfo = new ServerSpace.ServerInfo(IPAdd.Text,
Int32.Parse(PRTNo.Text));
t = new Thread(() =>
{
srv = new ServerSpace.Server(App.connectioninfo)
});
t.Start();
}
else
{
srv.stopserver();
MessageBox.Show("Server stopped.");
}
}
}
serveractive将一旦Server(ServerInfo)构造函数被执行,就设置为true。在srv.stopserver()抛出异常。
我应该在上面的代码中进行哪些更正?
我尝试了什么:
我尝试使用Application.Current.Dispatcher.Invoke,但是同样的错误结果。
"serveractive" will be set true once "Server(ServerInfo)" constructor gets executed. The exception is thrown at "srv.stopserver()".
What correction should I proceed with in the above code ?
What I have tried:
I tried using "Application.Current.Dispatcher.Invoke", but the same error results.
推荐答案
这篇关于访问在另一个线程中实例化的对象的成员。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!