在异步调用c#中包装同步函数

时间:2017-02-16 19:31:59

标签: c# asynchronous async-await task

我有一台服务器,它必须通过网络轮询设备,以获取信息,处理它然后将其发送给用户。 设备调查成为同步阻塞功能。

我的问题是:

如何使用Task或其他异步模式创建自己的异步函数版本来执行此函数???

考虑以下代码从设备获取信息:

IEnumerable<Logs> GetDataFromEquipment(string ipAddress)
        {
            Equipment equipment = new Equipment();
            //Open communication with equipment. Blocking code.
            int handler = equipment.OpenCommunication(ipAddress);
            //get data from equipment. Blocking code.
            IEnumerable<Logs> logs = equipment.GetLogs(handler);
            //close communication with equipment
            equipment.CloseCommunication(handler);

            return logs;
        }

由于

1 个答案:

答案 0 :(得分:1)

您可以使用async / await

 public async Task<IEnumerable<Logs>> GetDataFromEquipment(string ipAddress)
    {

        var task = Task.Run(() =>
        {
            Equipment equipment = new Equipment();
            //Open communication with equipment. Blocking code.
            int handler = equipment.OpenCommunication(ipAddress);
            //get data from equipment. Blocking code.
            IEnumerable<Logs> logs = equipment.GetLogs(handler);
            //close communication with equipment
            equipment.CloseCommunication(handler);

            return logs;
        });

        return await task;
    }