대기 가능* 익명 함수를 매개변수로 전달하기

먼저 코딩하세요. 이것이 제가 하려는 일입니다. 거의 다 됐지만 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){...}

질문에 대한 의견 (4)
해결책
private async void UpdateButton(Func post)
{
    if (!await post())
        ErrorBox.Text = "Error posting message.";
}

--편집--

UpdateButton(()=>Post("ss"));

private async void UpdateButton(Func post)
{
    if (!await post())
        this.Text = "Error posting message.";
}

public virtual async Task Post(string messageId)
{
    return await Task.Factory.StartNew(() => true);
}
해설 (6)

이것을 Action이 아닌 Task로 전달해야 합니다.

이렇게 하면 '기다릴 수 있는' 무언가를 제공합니다.

현재 코드를 고려할 때 이것이 작동할 것이라고 생각합니다:

private async Task UpdateButtonAsync(Task post)
{
    if (!await post)
        ErrorBox.Text = "Error posting message.";
}

// This will work if Post returns Task in the current API...
private void PostToTwitter()
{
    UpdateButtonAsync(new TwitterAction().Post("Hello, world!"));
}

작업`을 즉시 시작하지 않고 람다를 전달한 상태로 유지해야 하는 경우 람다가 비동기화될 이유가 없습니다. 이 경우 사용할 수 있습니다:

private async Task UpdateButtonAsync(Func post)
{
    if (!await post())
        ErrorBox.Text = "Error posting message.";
}

// This will work if Post returns Task in the current API...
private void PostToTwitter()
{
    UpdateButtonAsync(() => new TwitterAction().Post("Hello, world!"));
}

이렇게 하면 람다가 Task을 반환하고(Post가 이미 Task을 반환하므로 async/await 필요 없음) 업데이트 메서드가 람다를 실행하게 됩니다.

개인적으로 첫 번째 옵션(위)이 더 간단하다고 생각하며, 질문자님이 원하시는 방식일 가능성이 더 높다고 생각합니다. API가 이미 Task를 반환하고 있으므로 이를 전달하고 직접 대기하면 됩니다.

해설 (7)