在异步调用C#中包装一个同步函数 [英] Wrap a synchronous function in Asynchronous call c#
本文介绍了在异步调用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#中包装一个同步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文