如何在不冻结Windows Forms App 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;
        }

解决方法

我不确定那里发生了什么内部逻辑, 但是尝试将对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();