Wrap a synchronous function in Asynchronous call c#

自闭症网瘾萝莉.ら 提交于 2019-12-23 05:25:54

问题


I have a server, which must poll an equipment through the network, to obtain information, process it and then send it to the users. The equipment survey becomes a synchronous blocking function.

My question is:

How to create an own asynchronous function version to perform this function using Task or another asynchronous pattern???

Consider the following code to get information from equipment:

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;
        }

Thanks


回答1:


You can use 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;
    }


来源:https://stackoverflow.com/questions/42283026/wrap-a-synchronous-function-in-asynchronous-call-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!