首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#异步(工厂)方法& LINQ

C#异步(工厂)方法& LINQ
EN

Stack Overflow用户
提问于 2017-12-31 14:56:49
回答 1查看 694关注 0票数 0

我正在寻找一种正确的方法来设计我的代码。我有一个设备列表--通过以下方式创建的:

代码语言:javascript
复制
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在这里所说)中完成。

因此,我想诉诸某种类似工厂的东西:

代码语言:javascript
复制
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时,我希望反对自动创建.

提前谢谢!新年快乐!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-31 16:05:05

将方法转换为异步方式。

使用Linq选择所有任务,然后等待Task.WhenAll连接它们。

代码语言:javascript
复制
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();
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48043458

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档