我有一个async方法:

public async Task<string> GenerateCodeAsync()
{
    string code = await GenerateCodeService.GenerateCodeAsync();
    return code;
}

我需要从一个同步方法调用这个方法。

我如何才能做到这一点,而不必复制GenerateCodeAsync方法,以使其同步工作?

更新

但没有找到合理的解决方案。

但是,我看到HttpClient已经实现了这个模式

using (HttpClient client = new HttpClient())
{
    // async
    HttpResponseMessage responseAsync = await client.GetAsync(url);

    // sync
    HttpResponseMessage responseSync = client.GetAsync(url).Result;
}

当前回答

您可以使用同步方法生成器库(nuget)来生成此代码的同步版本。

使用方法如下:

[Zomp.SyncMethodGenerator.CreateSyncVersion]
public async Task<string> GenerateCodeAsync()
{
    string code = await GenerateCodeService.GenerateCodeAsync();
    return code;
}

它会生成GenerateCode方法,你可以同步调用。

将要生成的源是:

public string GenerateCode()
{
    string code = GenerateCodeService.GenerateCode();
    return code;
}

其他回答

您应该获取一个等待器(GetAwaiter()),并结束异步任务完成的等待(GetResult())。

string code = GenerateCodeAsync().GetAwaiter().GetResult();

如果你有一个名为“RefreshList”的异步方法,那么你可以从一个非异步方法调用该异步方法,如下所示。

Task.Run(async () => { await RefreshList(); });

我正在使用这种方法,它也将处理和传播来自底层异步任务的异常。

    private string RunSync()
    {
        var task = Task.Run(async () => await GenerateCodeService.GenerateCodeAsync());
        if (task.IsFaulted && task.Exception != null)
        {
            throw task.Exception;
        }

        return task.Result;
    }

我更喜欢非阻塞的方法:

            Dim aw1=GenerateCodeAsync().GetAwaiter()
            While Not aw1.IsCompleted
                Application.DoEvents()
            End While

这个线程上的大多数答案要么很复杂,要么会导致死锁。

下面的方法很简单,它将避免死锁,因为我们正在等待任务完成,然后才得到它的结果-

var task = Task.Run(() => GenerateCodeAsync()); 
task.Wait();
string code = task.Result;

此外,这里有一篇引用MSDN的文章,讨论了完全相同的事情- https://blogs.msdn.microsoft.com/jpsanders/2017/08/28/asp-net-do-not-use-task-result-in-main-context/