我開發了一個連接和操作設備的庫。 例如:TPL返回值和例外
public bool Connect(string ip)
{
try
{
// try connect to device
}
catch (Exception ex)
{
// trow custom exception
}
}
這是好的,但現在我決定在我的圖書館TPL包括。
我面臨的問題是如何返回值的邏輯。 而不是傳遞一個IP,你會傳遞一個IP列表。 想象一下,你要連接10個設備和5都ok和其他5指責我像一個代碼,如:
public Dictionary<Device, bool> Connect(List<Device> device)
{
try
{
// TPL try connect to device
}
catch (AggregatedException ex)
{
// trow custom exception
}
}
如果有人調用這個方法,他們將只收到exeption,在這種情況下,可以很容易,但例如,如果我有另一種方法,如Dictionary<Device, List<Logs>> GetLogs(List<Device> device)
我會有5個設備的數據和5個設備故障。
什麼是返回正確連接的結果和錯誤錯誤的最佳方法?連接可能由於多種原因而失敗。
UPDATE
我已經試過這樣:
public Dictionary<int, Task<string>> GetData3(int value)
{
Dictionary<int, Task<string>> dic = new Dictionary<int, Task<string>>();
Task<string>[] tasks = new Task<string>[value];
for (int i = 0; i < value; i++)
{
tasks[i] = Task.Factory.StartNew<string>((stateObject) =>
{
var a = (int)stateObject;
return a + " Test";
}, value);
dic.Add(i, tasks[i]);
}
Task.WaitAll(tasks);
return dic;
}
而在WS客戶:
Service1Client sc = new Service1Client();
var a = sc.GetData3(5);
如果我在return dic
打破我可以看到結果:
Id = 1, Status = RanToCompletion, Method = "{null}", Result = "5 Test"
但在var a
我只看到:
Id = 1, Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}"
有些客戶使用它作爲SDK,但我們有一個擴展使用這個相同的SDK來創建一個WCF。一些使用WCF的人使用php。你認爲創建什麼:DeviceResult:Device幷包含一個錯誤和異常的布爾值? – Eisenrich 2013-02-16 06:07:19
@Eisenrich:感覺就是這樣做,你完全否定使用TPL的一半好處。就我個人而言,我認爲基於任務的方法是最乾淨和最習慣的方法。 – 2013-02-16 07:52:58