2017-02-16 3 views
0

네트워크를 통해 장비를 폴링하여 정보를 얻고 처리 한 다음 사용자에게 보내야하는 서버가 있습니다. 장비 측량은 동기식 차단 기능이됩니다.비동기 호출에서 동기 함수 줄기 C#

내 질문은 :

어떻게 작업 또는 다른 비동기 패턴을 사용하여이 기능을 수행 할 수있는 자신의 비동기 기능 버전을 만들 ???

장비에서 정보를 얻기 위해 다음 코드를 고려하십시오

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

당신이 만드는'GetLogs' 비동기를 사용할 수 있습니다. – Servy

+0

어떻게해야합니까 ... –

+0

IO 메서드를 비동기로 만들어야합니다. post Open Communications 예를 들면. 그리고 먼저 그 방법을 알려 드리겠습니다. 귀하의 의사 소통은 어떻게 구현됩니까? .net 시설/클래스는 무엇입니까? –

답변

1

을 먼저 비동기/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; 
    } 
+0

Task.Run() ThreadPool에 스레드를 만들고 코드가 블로킹하는 경우이 경우 Task.Run을 올바르게 사용합니까 ??? –

+0

장비 호출 .GetLogs (핸들러); 몇 초 후에 응답하십시오. 스레드 풀에서 ThreadPool을 막는 것은 나쁜 습관이다. –

+0

'equipment.GetLogs (handler);를 호출하면 응답하는데 몇 초가 걸린다. ThreadPool에서 스레드를 차단 했으므로 악의적 인 연습을 읽었습니다 ... –