gpt4 book ai didi

c# - 如何在返回值之前等待回调完成?

转载 作者:行者123 更新时间:2023-12-04 10:50:31 27 4
gpt4 key购买 nike

public List<S3Object> ListObjects(string bucketname, string identityId)
{
List<S3Object> objectList = new List<S3Object>();

var request = new ListObjectsV2Request()
{
BucketName = bucket_name,
Prefix = identityId
};

Client.ListObjectsV2Async(request, (responseObject) =>
{
if (responseObject.Exception == null)
{
List<S3Object> list = new List<S3Object>();
responseObject.Response.S3Objects.ForEach((o) =>
{
objectList.Add(o);
});
}
else
{
Debug.Log(responseObject.Exception);
}
});
//return objectList;

// return the object after the callback is finished, e.g. added all the objects into objectList;
// ListObjectsV2Async method returns void, so it is not possible to use async and await. i guess?
}

我想在 ListObjectsV2Async 方法中的回调完成后返回 objectList 字段。但是,此方法异步运行,因此如果我只返回列表,它将返回一个空列表。那么我如何等到回调将所有对象添加到列表中后再返回?

最佳答案

一个 TaskCompletionSource可用于捕获回调的结果,允许方法等待。

例如

public Task<List<S3Object>> ListObjectsAsync(string bucket_name, string identityId) {
TaskCompletionSource<List<S3Object>> tcs = new TaskCompletionSource<List<S3Object>>();

var request = new ListObjectsV2Request() {
BucketName = bucket_name,
Prefix = identityId
};

Client.ListObjectsV2Async(request, (responseObject) => {
if (responseObject.Exception == null) {
tcs.TrySetResult(responseObject.Response.S3Objects.ToList());
} else {
Debug.Log(responseObject.Exception);
tcs.TrySetException(responseObject.Exception);
}
});

// return the object after the callback is finished
return tcs.Task;
}

现在允许
List<S3Object> objectList = await myClient.ListObjectsAsync("bucket_name_here", "identityId_here");

关于c# - 如何在返回值之前等待回调完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59501487/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com