C# 2个Winform应用程序引用的托管DLL。Winform 1启动Winform 2,但上下文是共享的,除非两者单独执行
我有两个WinForm客户端应用程序,它们引用相同的托管DLL(用C++/CLI编写),目的是连接到本机套接字服务器 两个Winform应用程序在单独启动时运行良好,但在一个启动另一个时运行不正常 假设启动了客户端Winform 1。它按照预期创建自己的套接字和上下文,然后作为一个单独的线程启动Winform 2 Winform 2还将作为本机服务器的客户端打开自己的套接字,但当Winform 2关闭其套接字并退出时,Winform 1停止工作,因为它似乎认为它是Winform 2。因此,WinForm 1的任何服务器请求都会失败,因为它的套接字变成了先前由套接字2关闭的套接字 这种行为对我来说是新的,但显然它必须扩展到变量“SOCKET\u id”之外 Winform2应该作为一个单独的进程而不是执行Application.Run(Winform2)的典型线程启动吗 谢谢C# 2个Winform应用程序引用的托管DLL。Winform 1启动Winform 2,但上下文是共享的,除非两者单独执行,c#,.net,winforms,c++-cli,winforms-interop,C#,.net,Winforms,C++ Cli,Winforms Interop,我有两个WinForm客户端应用程序,它们引用相同的托管DLL(用C++/CLI编写),目的是连接到本机套接字服务器 两个Winform应用程序在单独启动时运行良好,但在一个启动另一个时运行不正常 假设启动了客户端Winform 1。它按照预期创建自己的套接字和上下文,然后作为一个单独的线程启动Winform 2 Winform 2还将作为本机服务器的客户端打开自己的套接字,但当Winform 2关闭其套接字并退出时,Winform 1停止工作,因为它似乎认为它是Winform 2。因此,Win
private void LaunchWinForm2Button_Click(object sender, EventArgs e)
{
System.Threading.Thread myThread =
new System.Threading.Thread(new System.Threading.ThreadStart(StartWinForm2));
myThread.Start();
}
private void StartWinForm2()
{
CSharpFormApp.WinForm2 theWinForm2 = new CSharpFormApp.WinForm2();
Application.Run(theWinForm2);
}
问题在于指向C++/CLI DLL中本机数据的全局指针。 由于WinForms通过几个C++/CLI接口获取数据,因此最初更容易让它们通过全局指针访问本机数据
NativeLayer::NativeLayerData* native_data;
public ref class Test1Implementer : ITest1
{
virtual bool TestConnect()
{
bool success = native_data->Connect();
return success;
}
};
public ref class Test2Implementer : ITest2
{
virtual bool TestDisconnect()
{
bool success = native_data->Disconnect();
return success;
}
};
最终,这种实现会再次困扰我,但这些都是试图在工业应用中使用globals的危险
一旦我摆脱了指向本机数据的托管全局指针,一切都会按预期运行。下面是一个可能的解决方案,它允许使用嵌套接口进行多线程处理:
public ref class TestsImplementer : ITests
{
private:
NativeLayer::NativeLayerData* native_data;
public:
TestsImplementer()
{
native_data = new NativeLayer::NativeLayerData();
}
ref class Test1Implementer : ITest1
{
virtual bool TestConnect(TestsImplementer^ tests)
{
bool success = tests->native_data->Connect();
return success;
}
};
ref class Test2Implementer : ITest2
{
virtual bool TestDisconnect(TestsImplementer^ tests)
{
bool success = tests->native_data->Disconnect();
return success;
}
};
};
你能提供一些代码来说明你是如何实际启动WinForm2的吗?嘿,迈克。WinForm 2启动良好,完成了它需要做的一切。我已经添加了代码。这个问题似乎是在C++库中。你有任何全局变量或静态变量吗?似乎在进程范围中声明了一些内容。您如何准确地管理客户端套接字?谢谢Oguz Ozgul。你的评论是关键的洞察。