【问题标题】:How to wait for the network request to be fulfilled asynchronously, but process the result in the main thread?如何等待网络请求异步完成,但在主线程中处理结果?
【发布时间】:2018-07-30 22:57:18
【问题描述】:

我正在使用 Unity3d,支持 .NET 4.6,并且需要处理网络请求。我想在异步问题上做到这一点,但由于统一不是线程安全的,你不能从除主线程之外的任何线程访问它的任何 api。

我确信WebClient 的异步方法的回调在后台线程中触发,所以我前段时间放弃了那个变体。

但是最近在我的项目中添加了 .NET 4.6,我能够以这样的方式使用 TAP 和 async/await,在异步等待之后 - 使用 await,我的代码主要执行统一线。我也想通过处理网络请求来实现类似的目标。是否有一些基于任务的 Api 用于网络,或者在主线程中执行的东西,只是延迟了?

【问题讨论】:

  • 避免在 Unity 中使用 await。只需在另一个线程中使用 WebClient,然后在请求完成时在主线程中进行回调....顺便说一下,您可以使用 Unity 的 WWWUnityWebRequst 类来处理没有任何线程的 Web 请求。
  • @Programmer 我正在为WebClient 设置DownloadStringAsync 的回调,并收到一个错误,当您从另一个线程访问它的API 时统一给您,所以我认为所有这些回调都是从用于等待的后台线程。至于等待 - 我发现 TAP 比异步代码的回调和协程优雅得多,而且我知道基于协程的 WWW 类(和新的 UnityWebRequest)
  • 好的。发布你的代码,错误行,我会告诉你一个解决方案。
  • @Programmer .NET 4.6 被添加到 Unity 中,部分原因是为了能够使用 TAP,不知道你为什么不建议这样做
  • @CamiloTerevinto 我知道新的支持,并且之前已经在这里留下了答案。我只是认为使用asyncawait 不会解决当前OP 的问题。在 Unity 或游戏应用程序中应避免使用它,因为 async 方法每次使用时都会分配一个新的 Task 对象。这个问题仍然存在于 C# 6 中。在修复之前,如果大量使用它可能会减慢游戏速度。应该改为协程。

标签: c# unity3d network-programming async-await .net-4.6


【解决方案1】:

啊,.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;
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    • 2013-03-27
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多