如何将这些代码更改为c#样式?

T_T*_*T_T 3 .net c# async-await

这是我的HttpService类,它工作正常.但它看起来很奇怪,每个函数中的代码都大致相同.我应该在每个函数中编写try/catch,特别是TaskCanceledException,如果我没有在这里捕获它,我的应用程序将终止.有人能给我一些关于如何优化代码的例子吗?

[Export(typeof(IDataSource))]
public class HttpService : IDataSource
{
    HttpClient client = new HttpClient();
    public HttpService()
    {
        client.BaseAddress = new Uri("https://localhost:3721");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public void Initialize(CurrentUser currentUser)
    {
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
            Convert.ToBase64String(Encoding.UTF8.GetBytes(currentUser.Name + ":" + currentUser.Password)));
    }

    public async Task<IEnumerable<User>> getUsers()
    {
        try
        {
            var response = await client.GetAsync("api/User");
            //response.EnsureSuccessStatusCode(); // Throw on error code.
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<IEnumerable<User>>();
                return result;
            }
            else
            {
                return null;
            }
        }
        catch (Newtonsoft.Json.JsonException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (TaskCanceledException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return null;
    }

    public async Task<IEnumerable<permission>> getPermission()
    {
        try
        {
            var response = await client.GetAsync("api/User");
            //response.EnsureSuccessStatusCode(); // Throw on error code.
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<IEnumerable<permission>>();
                return result;
            }
            else
            {
                return null;
            }
        }
        catch (Newtonsoft.Json.JsonException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (TaskCanceledException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return null;
    }

    public async Task<CurrentUser> getCurrentUserInfo(User user)
    {
        try
        {
            var response = await client.GetAsync("api/User?name=" + user.Name);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsAsync<CurrentUser>();
                return result;
            }
            else
            {

                return null;
            }
        }
        catch (Newtonsoft.Json.JsonException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        catch (TaskCanceledException ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return null;
    }

}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

如果我没有在这里抓到它,我的申请将终止.

不,这根本不是真的; 调用它的代码也有机会(实际上是责任)来处理错误.例如:

try {
    var permission = await getPermission();
    //...
} catch(Exception ex) {
    // log, whatever
}
Run Code Online (Sandbox Code Playgroud)

将异常处理放在最合适的位置将减少async方法中不必要的代码.你现在正在做的是让你的async方法假装没有发生任何不好的事情 - 这不是最好的做法.