【发布时间】:2021-06-12 17:12:02
【问题描述】:
总而言之:我有一个带有套接字的服务器的控制台应用程序,如果用户键入 -w 作为 args[],我希望具有在 WPF 中的功能。问题是当我调用 RunServer() 方法时,侦听器正在侦听并且 WPF 窗口被冻结。我想要对窗口进行的唯一更新是使用 SendEvent() 方法,该方法将消息添加到窗口 TextBox。我尝试创建线程、后台工作人员,但似乎没有任何效果。当它实际转到更改文本的行时,会出现一个异常,指出“调用线程无法访问此对象,因为不同的线程拥有它 “。有人可以提出解决方案吗?我没有做的唯一建议是“切换到 .Net Core”。
if (GUI)
{
Window1 window = new Window1();
RunServer();
}
public Window1(bool saving, bool logging)
{
InitializeComponent();
IsSavingLogging(saving, logging);
Events.Text += "Test\r\n";
try
{
Show();
Update("Test2\r\n");//this doesn't work
}
catch (Exception e)
{
// if there was an error in the processing- catch it and note the details
//Update( "Exception: " + e.ToString());
}
}
public static void RunServer(Window1 pWindow1)
{
TcpListener listener;
Socket connection;
Handler requestHandler;
try
{
//create a tcp socket to listen on port 43 fo incoming requests
// and start listening
listener = new TcpListener(IPAddress.Any, 43);
SendEvent( "Server Started", GUI,pWindow1);
listener.Start();
while (true)
{
connection = listener.AcceptSocket();
requestHandler = new Handler();
Thread t = new Thread(() => requestHandler.DoRequest(connection,pWindow1));
t.Start();
}
}
catch (Exception e)
{
// if there was an error in the processing- catch it and note the details
SendEvent( "Exception: " + e.ToString(),GUI,pWindow1);
}
}
private static void SendEvent(string pMessage, bool pGui,Window1 window1)
{
if (pGui)
{
window1.Events.Text += pMessage+"\r\n";
}
else {
Console.WriteLine(pMessage);
}
}
【问题讨论】:
-
我不确定您的控制台应用程序和 WPF 应用程序之间的关系,但您至少可以修复异常。 stackoverflow.com/questions/9732709/…
标签: c# wpf multithreading