我有 MVP 应用程序 C#、.NET 4、WinForms。它使用通过 NamedPipe 与第三方应用程序通信的 Bridge 类。命令流程是这样的:View → Presenter → Manager → Bridge → Client 并以相反的顺序返回。View 已准备好进行多任务处理。我通过增加事件结果在 Manager 中拆分反向链,但这无济于事。
// View class
public void AccountInfo_Clicked() { presenter.RequestAccountInfo(); }
public void UpdateAccountInfo(AccountInfo info)
{
if (pnlInfo.InvokeRequired)
pnlInfo.BeginInvoke(new InfoDelegate(UpdateAccountInfo), new object[] {info});
else
pnlInfo.Update(info);
}
// Presenter class
public void RequestAccountInfo() { manager.RequestAccountInfo(); }
private void Manager_AccountInfoUpdated(object sender, AccountInfoEventArgs e)
{
view.UpdateAccountInfo(e.AccountInfo);
}
// Manager class
public void RequestAccountInfo()
{
AccountInfo accountInfo = bridge.GetAccountInfo();
OnAccountInfoUpdated(new AccountInfoEventArgs(accountInfo));
}
// Bridge class
public AccountInfo GetAccountInfo() { return client.GetAccountInfo(); }
// Client class
public AccountInfo GetAccountInfo()
{
string respond = Command("AccountInfo");
return new AccountInfo(respond);
}
private string Command(string command)
{
var pipe = new ClientPipe(pipeName);
pipe.Connect();
return pipe.Command(command);
}
我想在命令处理期间解冻 UI。还有其他可以执行的命令。最后,所有命令都到达Command(string command)
客户端中的方法。
我试图通过使用 task 和 ContinueWith 来打破 Manager 中的链,但它导致管道无法连接。原因是客户端不是线程安全的。
// Manager class
public void RequestAccountInfo()
{
var task = Task<AccountInfo>.Factory.StartNew(() => bridge.GetAccountInfo());
task.ContinueWith(t => { OnAccountInfoUpdated(new AccountInfoEventArgs(t.Result)); });
}
我的问题是:在哪里使用 Task、ContinueWith 以及在哪里锁定?
我认为我可以锁定只是Command(string command)
因为它是最终的方法。
private string Command(string command)
{
lock (pipeLock)
{
var pipe = new ClientPipe(pipeName);
pipe.Connect();
return pipe.Command(command);
}
}
我可以使用任务,Command
在客户端类中等待吗?