问题
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