我正在寻找一种正确的方法来设计我的代码。我有一个设备列表--通过以下方式创建的:
public void LoadDevices()
{
using (XmlReader xmlRdr = new XmlTextReader(deviceConfigPath))
deviceList = (from deviceElem in XDocument.Load(xmlRdr).Element("devices").Elements("device")
where (string)deviceElem.Attribute("type") == "mks247"
select (SmartCatDeviceBase)new mks247Device(
(string)deviceElem.Attribute("ip"),
(string)deviceElem.Attribute("name"),
(string)deviceElem.Attribute("id"),
(bool)deviceElem.Attribute("autoconnect")
)).ToList();
}类型转换到SmartCatDeviceBase是必要的,因为我有更多的不同类型的设备(具有相同的基类)进入该列表。
现在的问题是“自动连接”:它要求设备打开异步网络连接,这不应该在构造函数(正如Stephen在这里所说)中完成。
因此,我想诉诸某种类似工厂的东西:
private async Task<SmartCatDeviceBase> Createmks247DeviceAsync(string host, string name, string id, bool autoconnect = true)
{
mks247Device dev = new mks247Device(host, name, id); // Now without the autoconnect, that shouldn't be in the constructor.
// Connect.
if (autoconnect)
{
bool connected = await dev.ConnectAsync();
// Begin to poll for data.
dev.BeginPolling();
}
return dev;
}所以问题是:我怎样才能使代码工作呢?因为在我的LINQ代码中使用Createmks247DeviceAsync而不是新的mks247Device()是行不通的:
类型"System.Threading.Tasks.Task“不能转换为"SmartCatDeviceBase”。
在select语句中使用await关键字也是不可能的.
或者有没有其他方法来正确设计这样的代码呢?在构造函数中设置一个自动更正标志,然后“从外部”连接,似乎违反了OOP:当有一个autoconnect选项时,当我设置为true时,我希望反对自动创建.
提前谢谢!新年快乐!
发布于 2017-12-31 16:05:05
将方法转换为异步方式。
使用Linq选择所有任务,然后等待Task.WhenAll连接它们。
public async Task LoadDevicesAsync() {
using (XmlReader xmlRdr = new XmlTextReader(deviceConfigPath)) {
var getdeviceListTasks = (from deviceElem in XDocument.Load(xmlRdr).Element("devices").Elements("device")
where (string)deviceElem.Attribute("type") == "mks247"
select Createmks247DeviceAsync(
(string)deviceElem.Attribute("ip"),
(string)deviceElem.Attribute("name"),
(string)deviceElem.Attribute("id"),
(bool)deviceElem.Attribute("autoconnect")
));
var devices = await Task.WhenAll(getdeviceListTasks);
deviceList = devices.ToList();
}
}https://stackoverflow.com/questions/48043458
复制相似问题