반응형
비동기 액션 대리자 메서드를 어떻게 구현합니까?
작은 배경 정보.
웹 API 스택을 배우고 있으며 Success 및 ErrorCodes와 같은 매개 변수를 사용하여 모든 데이터를 "Result"개체 형식으로 캡슐화하려고합니다.
그러나 다른 방법은 다른 결과와 오류 코드를 생성하지만 결과 개체는 일반적으로 동일한 방식으로 인스턴스화됩니다.
시간을 절약하고 C #의 async / await 기능에 대해 자세히 알아 보려면 웹 API 작업의 모든 메서드 본문을 비동기 작업 대리자로 래핑하려고하지만 약간의 걸림에 빠졌습니다.
다음과 같은 클래스가 주어집니다.
public class Result
{
public bool Success { get; set; }
public List<int> ErrorCodes{ get; set; }
}
public async Task<Result> GetResultAsync()
{
return await DoSomethingAsync<Result>(result =>
{
// Do something here
result.Success = true;
if (SomethingIsTrue)
{
result.ErrorCodes.Add(404);
result.Success = false;
}
}
}
Result 객체에서 작업을 수행하고 반환하는 메서드를 작성하고 싶습니다. 일반적으로 동기식 방법을 통해
public T DoSomethingAsync<T>(Action<T> resultBody) where T : Result, new()
{
T result = new T();
resultBody(result);
return result;
}
그러나 async / await를 사용 하여이 메소드를 비동기 메소드로 어떻게 변환합니까?
이것이 내가 시도한 것입니다.
public async Task<T> DoSomethingAsync<T>(Action<T, Task> resultBody)
where T: Result, new()
{
// But I don't know what do do from here.
// What do I await?
}
async
의 상당 Action<T>
하다 Func<T, Task>
나는 이것이 당신이 찾고있는 무엇을 믿고, 그래서 :
public async Task<T> DoSomethingAsync<T>(Func<T, Task> resultBody)
where T : Result, new()
{
T result = new T();
await resultBody(result);
return result;
}
그래서 이것을 구현하는 방법은 다음과 같습니다.
public Task<T> DoSomethingAsync<T>(Action<T> resultBody) where T : Result, new()
{
return Task<T>.Factory.StartNew(() =>
{
T result = new T();
resultBody(result);
return result;
});
}
참고 URL : https://stackoverflow.com/questions/20624667/how-do-you-implement-an-async-action-delegate-method
반응형
'programing tip' 카테고리의 다른 글
대기중인 performSelector : afterDelay 호출 취소 (0) | 2020.07.23 |
---|---|
“--allow-file-access-from-files”모드에서 Chrome을 사용하여 HTML을 시작하는 방법은 무엇입니까? (0) | 2020.07.23 |
WCF 서비스 코드를 디버깅하려고 할 때“시계 추가”기능에서“표현식 평가 기에서 내부 오류”가 표시됨 (MSVS 2013) (0) | 2020.07.23 |
foreach 루프에서 배열 요소를 어떻게 제거합니까? (0) | 2020.07.23 |
안드로이드 장치를 확인하는 방법은 HDPI 화면 또는 MDPI 화면입니까? (0) | 2020.07.22 |