如何异步等待网络请求完成,但在主线程中处理结果?
How to wait for the network request to be fulfilled asynchronously, but process the result in the main thread?
我正在使用支持 .NET 4.6 的 Unity3d,并且需要处理网络请求。我想在异步问题上这样做,但由于 unity 不是线程安全的,你不能从主线程以外的任何线程访问它的任何一个api。
我确定 WebClient
的异步方法的回调在后台线程中触发,所以我之前放弃了那个变体。
但是随着最近将 .NET 4.6 添加到我的项目中,我能够以这种方式使用 TAP 和 async/await,在异步等待之后 - 使用 await
,我的代码在主统一线程中执行。我也想通过处理网络请求来实现类似的目标。那里是否有一些基于任务的 Api 用于联网,或者在主线程中执行的东西,只是延迟了?
啊,.NET 4.6
为 WebClientClass 添加了新方法,现在异步方法有 an overload returning a Task
我是这样使用的:
string profilePicUrl = await _apiCaller.GetProfilePictureUrlAsync();
using(var web = new WebClient())
{
byte[] picBytes = await web.DownloadDataTaskAsync(profilePicUrl);
// unity api here works because we are back in the main thread
// as async returns you to the contex in which you started
var profilePicTexture = new Texture2D(4, 4);
profilePicTexture.LoadImage(picBytes);
return profilePicTexture;
}
我正在使用支持 .NET 4.6 的 Unity3d,并且需要处理网络请求。我想在异步问题上这样做,但由于 unity 不是线程安全的,你不能从主线程以外的任何线程访问它的任何一个api。
我确定 WebClient
的异步方法的回调在后台线程中触发,所以我之前放弃了那个变体。
但是随着最近将 .NET 4.6 添加到我的项目中,我能够以这种方式使用 TAP 和 async/await,在异步等待之后 - 使用 await
,我的代码在主统一线程中执行。我也想通过处理网络请求来实现类似的目标。那里是否有一些基于任务的 Api 用于联网,或者在主线程中执行的东西,只是延迟了?
啊,.NET 4.6
为 WebClientClass 添加了新方法,现在异步方法有 an overload returning a Task
我是这样使用的:
string profilePicUrl = await _apiCaller.GetProfilePictureUrlAsync();
using(var web = new WebClient())
{
byte[] picBytes = await web.DownloadDataTaskAsync(profilePicUrl);
// unity api here works because we are back in the main thread
// as async returns you to the contex in which you started
var profilePicTexture = new Texture2D(4, 4);
profilePicTexture.LoadImage(picBytes);
return profilePicTexture;
}