从不同线程上的另一个类调用WPF MainWindow类中的方法



我试图通过调用MainWindow类中的方法来编辑主窗口项。我想叫它哪里是在一个单独的线程在一个单独的类。

这是主窗口类,我在服务器类中调用start方法,该方法创建一个新线程来执行服务器。您还可以看到我想调用的两个方法来更改主窗口

中的标签
public partial class MainWindow : Window
{

public MainWindow()
{
InitializeComponent();
Server server = new Server();
server.Start();

}

public void UpdateMessage(string message)
{
Message.Content = message;
}
public void UpdateAddress(string address)
{
Address.Content = address;
}

这是服务器类,打开套接字并监听客户端。这一切都工作,我只是想更新WPF窗口与套接字正在做什么。

public class Server
{
public void Start()
{
//Create and start threads
var serverTask = new Task(ExecuteServer);
serverTask.Start();
}
/// <summary>
/// Start and run TCP IP server/connection
/// </summary>
public void ExecuteServer()
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
try
{
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);

// I want to call the methods here
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
var clientSocket = listener.AcceptAsync();
var reciveThread = new Thread(() => ReciveAndEnqueueCommand(clientSocket, listener));
reciveThread.Start();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}

尝试以下操作:

var mw = ((MainWindow)Application.Current.MainWindow);
if(mw!=null)
mw.Dispatcher.Invoke(() =>
{
mw.UpdateMessage("msg");
});

正如@Fildor所评论的那样,使用IProgress是我能够让它工作的方式。我还使用了@yassinMi发布的代码来调用MainWindow类中的方法,所以谢谢你们。下面是我用来得到我的解决方案的代码。

public class Server
{
//Create the progress item outside the second thread
public Progress<string> _addressProgress = new Progress<string>(a =>
{
//get the main window element like yassinMi commented
var mw = ((MainWindow)Application.Current.MainWindow);
if (mw != null)
mw.Dispatcher.Invoke(() =>
{
mw.UpdateAddress(a);
});
});
public void Start()
{
//Create and start threads
//Pass progress item to the execute server method
var serverTask = new Task(() => ExecuteServer(_addressProgress));
serverTask.Start();
}

/// <summary>
/// Start and run TCP IP server/connection
/// </summary>
public void ExecuteServer(IProgress<string> addressProgress)
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);

try
{
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
//Report the progress to update the ui element
addressProgress.Report("Test");
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
var clientSocket = listener.AcceptAsync();
var reciveThread = new Thread(() => ReciveAndEnqueueCommand(clientSocket, listener));
reciveThread.Start();
}

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

相关内容

  • 没有找到相关文章

最新更新