首页 > 解决方案 > 如何在不冻结 Windows 窗体应用程序 C# WindowsPCL 的情况下获取客户端

问题描述

我正在尝试从我的网站获取发布数据以在 Windows 窗体应用程序中使用。当我尝试调用下面的方法来获取我网站的 WordPressClient 时,整个表单冻结并且没有响应。

public static async Task<WordPressClient> GetClient()
        {
            //JWT authentication
            var client = new WordPressClient("http://website.com");
            client.AuthMethod = AuthMethod.JWT;

            //Form freezes on this line
            await client.RequestJWToken("email", "password");

            return client;
        }

标签: c#wordpressasynchronoustaskwordpress-rest-api

解决方案


我不确定那里发生的内部逻辑是什么,但尝试将WordPressClient构造函数的调用包装成Task.Run

public static async Task<WordPressClient> GetClient()
{
    try
    {
        WordPressClient client = null;

        await Task.Run(() =>
        {
            //JWT authentication
            client = new WordPressClient("http://website.com");
            client.AuthMethod = AuthMethod.JWT;
        });

        //Form freezes on this line
        await client.RequestJWToken("email", "password");

        return client;
    }
    catch (Exception e) // this should be more specific Error Handler
    {
        //Console.WriteLine(e.Message);
        throw;
    }
}

另外,请确保正在运行的代码正在GetClient()运行它async

var client = await GetClient();

推荐阅读