在异步调用C#中包装一个同步函数

编程入门 行业动态 更新时间:2024-10-25 10:27:37
本文介绍了在异步调用C#中包装一个同步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个服务器,该服务器必须通过网络轮询设备,以获取信息,对其进行处理,然后将其发送给用户. 设备调查成为同步阻止功能.

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.

我的问题是:

如何创建自己的异步功能版本以使用Task或其他异步模式执行此功能?

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

谢谢

推荐答案

您可以使用async/await

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

更多推荐

在异步调用C#中包装一个同步函数

本文发布于:2023-11-23 10:30:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621113.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!