我有MVP應用程序C#,.NET 4,WinForms。它使用Bridge類,通過NamedPipe與第三方應用程序進行通信。 命令流程如下:查看→演示器→管理器→橋接器→客戶端 然後按相反的順序返回。視圖準備好多任務處理。我在Manager中通過上升事件來分割反向鏈,但結果不起作用。哪裏打破任務鏈,ContinueWith,鎖
// 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。還有其他可以執行的命令。最後所有的命令都在Client中的Command(string command)
方法。
我試圖通過使用任務和ContinueWith打破管理器中的鏈,但它導致管道無法連接。原因是客戶端不是線程安全的。
// Manager class
public void RequestAccountInfo()
{
var task = Task<AccountInfo>.Factory.StartNew(() => bridge.GetAccountInfo());
task.ContinueWith(t => { OnAccountInfoUpdated(new AccountInfoEventArgs(t.Result)); });
}
我的問題是:在哪裏使用任務,ContinueWith和在哪裏鎖?
我想我只能鎖定Command(string command)
,因爲這是最終的方法。
private string Command(string command)
{
lock (pipeLock)
{
var pipe = new ClientPipe(pipeName);
pipe.Connect();
return pipe.Command(command);
}
}
我可以在Client類中使用Task,Wait在Command
中嗎?
所以你的應用程序應該是異步的一路? – ilansch
是的,我希望。有5-10個可以打開的視圖。他們每個人都有自己的Bridge和Client的副本。還有從每個視圖可以給出5-6個命令。所有這些都必須發送到其他線程的某處。但我不知道在命令鏈中的哪個位置。並且還在鎖鏈中。 –
使用'Task'時會拋出什麼錯誤? – MoonKnight