Kam*_*mil 0 c# asynchronous async-await grpc
我的async方法如下:
public async Task<List<object>> handleSummaryOfWallets()
{
string token = giveMeToken("URL AND CREDS");
Channel channel = new Channel("NANANANA GIROUD", ChannelCredentials.Insecure);
OMGadminAPI.OMGadminAPIClient client = new OMGadminAPI.OMGadminAPIClient(channel);
var summaryBalancesParams = new OMGadminAPIGetCurrenciesSummariesParams();
summaryBalancesParams.AdminAuthTokenSecret = token;
List<object> summariesCurrenciesOMGadmin = new List<object>();
using (var call = client.GetCurrenciesSummaries(summaryBalancesParams))
{
while (await call.ResponseStream.MoveNext())
{
OMGadminAPICurrencySummary currencySummary = call.ResponseStream.Current;
summariesCurrenciesOMGadmin.Add(currencySummary);
Console.WriteLine(summariesCurrenciesOMGadmin);
}
return summariesCurrenciesOMGadmin;
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,上述async方法返回对象列表。我调用这个方法如下:
var listOfBalances = balances.handleSummaryOfWallets().Wait();
Run Code Online (Sandbox Code Playgroud)
它给了我错误:
错误 CS0815:无法将 void 分配给隐式类型的变量
从错误中,我明白这不是调用async方法的正确方法。但是我需要从async获取的数据中读取准备好的对象列表。它的请求-响应,没有真正的稳定流。所以我每个请求只需要生成一次这个列表。我正在使用gRPC框架进行 RPC 调用。
请帮我获取这些数据并准备好使用。
该Task.Wait方法等待Task完成执行。它返回void。这就是异常的原因。
现在为了克服异常并读取返回值,一种方法如其他答案和评论中所述;await调用如下:
public async void TestAsync()
{
var listOfBalances = await handleSummaryOfWallets();
}
Run Code Online (Sandbox Code Playgroud)
请注意,您的调用async方法现在也应该是方法。
当您调用Wait代码时,看起来您想要立即得到结果;你没有其他事情要做,这不取决于结果。在这种情况下,您可以选择async通过调用来停止链Wait。但是你需要做一些改变,如下所示:
public void TestAsync()
{
var task = handleSummaryOfWallets();//Just call the method which will return the Task<List<object>>.
task.Wait();//Call Wait on the task. This will hold the execution until complete execution is done.
var listOfBalances = task.Result;//Task is executed completely. Read the result.
}
Run Code Online (Sandbox Code Playgroud)
请注意,调用方法不再是async. 其他解释在代码注释中给出。
上述代码的其他简短替代如下:
public void TestAsync()
{
var listOfBalances = handleSummaryOfWallets().Result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1027 次 |
| 最近记录: |