所以,这是布局:
frmClient = uses frmLogin (LoginWindow) which has OnLoginEvent
此事件由 frmClient 接收,并将更新状态栏(没有调用)
frmClient 还使用了 ClassMatrix(矩阵),它有 OnClientConnectEvent,由 ClassServer 的事件调用
frmClient 正在接收来自 Matrix 的事件 <- ClassServer
但尝试更新状态栏时显示多线程错误
frmClient <- frmLogin's event works to update
frmClient <- Matrix <- Server's event errors with multithread
服务器:
public event EventHandler<string> OnConnectionAcceptedEvent;
protected virtual void ConnectionAccepted(string e) { OnConnectionAcceptedEvent?.Invoke(this, e); }
服务器
Task.Run(new Action(async() =>.....
Client = new TcpClient("127.0.0.1", Port);
if (ID == 9999)
{
Guid _guid = Guid.NewGuid();
StageOneReaderServerStarted(ID.ToString());
ConnectionAccepted(ID.ToString()); // This is the command
GuidCreated(_guid.ToString());
SentGuid(_guid.ToString());
StartedStandardEncryption(ID.ToString());
StageTwoReaderServerStarted(ID.ToString());
}
矩阵:
public event EventHandler<string> ConnectionUpdateEvent;
Servers.Servers[Servers.Servers.FindIndex(f => f.ID == id)].OnConnectionAcceptedEvent += Matrix_OnConnectionAcceptedEvent;
private void Matrix_OnConnectionAcceptedEvent(object sender, string e)
{
ConnectionUpdateEvent?.Invoke(this, e);
Console.WriteLine($"Connection Accepted: {e}");
}
客户:
Matrix.ConnectionUpdateEvent += Matrix_ConnectionUpdateEvent;
LoginWindow.OnLogin += LoginWindow_OnLoginEvent;
protected virtual Matrix_ConnectionUpdateEvent(object sender, string e)
{
statusPanel.Text = "Loggiasfasfasfng in..."; //works
}
protected virtual void LoginWindow_OnLoginEvent(object sender, string data)
{
statusPanel.Text = "Logging in..."; //works
Matrix.SentLogin(data);
}
所以,显然状态栏有 .Parent.Invoke / .Parent/InvokeRequired
现在可以了,我花了很长时间才弄清楚
if (statusPanel.Parent.InvokeRequired)
{
statusPanel.Parent.Invoke(new MethodInvoker(delegate { statusPanel.Text = "fffff"; }));
}