먼저 코딩하세요. 이것이 제가 하려는 일입니다. 거의 다 됐지만 UpdateButton 메서드에서 매개 변수를 정의한 방식을 수정해야 할 것 같습니다.
private async void UpdateButton(Action<bool> post)
{
if (!await post())
ErrorBox.Text = "Error posting message.";
}
private void PostToTwitter()
{
UpdateButton(async () => await new TwitterAction().Post("Hello, world!"));
}
private void PostToFacebook()
{
UpdateButton(async () => await new FacebookAction().Post("Hello, world!"));
}
안타깝게도 '!await post()`는 ''void'유형이 대기 가능하지 않기 때문에 작동하지 않습니다. '그래서 질문은 이 메서드에서 대기 가능 매개 변수를 지원하도록 매개 변수를 어떻게 정의해야 하느냐는 것입니다.
트위터 액션().포스트()를 정의하는 방법은 다음과 같습니다...
public virtual async Task<bool> Post(string messageId){...}
private async void UpdateButton(Func<Task<bool>> post)
{
if (!await post())
ErrorBox.Text = "Error posting message.";
}
--편집--
UpdateButton(()=>Post("ss"));
private async void UpdateButton(Func<Task<bool>> post)
{
if (!await post())
this.Text = "Error posting message.";
}
public virtual async Task<bool> Post(string messageId)
{
return await Task.Factory.StartNew(() => true);
}
이것을 Action
이 아닌 Task
로 전달해야 합니다.
이렇게 하면 '기다릴 수 있는' 무언가를 제공합니다.
현재 코드를 고려할 때 이것이 작동할 것이라고 생각합니다:
private async Task UpdateButtonAsync(Task<bool> post)
{
if (!await post)
ErrorBox.Text = "Error posting message.";
}
// This will work if Post returns Task<bool> in the current API...
private void PostToTwitter()
{
UpdateButtonAsync(new TwitterAction().Post("Hello, world!"));
}
작업`을 즉시 시작하지 않고 람다를 전달한 상태로 유지해야 하는 경우 람다가 비동기화될 이유가 없습니다. 이 경우 사용할 수 있습니다:
private async Task UpdateButtonAsync(Func<Task<bool>> post)
{
if (!await post())
ErrorBox.Text = "Error posting message.";
}
// This will work if Post returns Task<bool> in the current API...
private void PostToTwitter()
{
UpdateButtonAsync(() => new TwitterAction().Post("Hello, world!"));
}
이렇게 하면 람다가 Task<bool>
을 반환하고(Post
가 이미 Task<bool>
을 반환하므로 async
/await
필요 없음) 업데이트 메서드가 람다를 실행하게 됩니다.
개인적으로 첫 번째 옵션(위)이 더 간단하다고 생각하며, 질문자님이 원하시는 방식일 가능성이 더 높다고 생각합니다. API가 이미 Task
를 반환하고 있으므로 이를 전달하고 직접 대기
하면 됩니다.