【问题标题】:Trying to call WPF program from Console [duplicate]试图从控制台调用 WPF 程序 [重复]
【发布时间】: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);
            }
        }

【问题讨论】:

标签: c# wpf multithreading


【解决方案1】:

如果您因为与我处于同一位置而来到这里,我发现我可以创建另一个无响应的窗口并将文本放在那里。我加了

this.Show();
Thread.Sleep(15000);//15 seconds timeout
this.Close();

这就是工作 此外,您必须从一个单独的线程调用此窗口,该线程是

Thread t= new Thread(()=> window=new Window(pMessage));

至少我希望这对某人有所帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2017-11-23
    • 2012-02-22
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    相关资源
    最近更新 更多