为了账号安全,请及时绑定邮箱和手机立即绑定

任务扩展以应对应用范围内的服务调用

任务扩展以应对应用范围内的服务调用

C#
LEATH 2021-07-01 04:28:10
我在 xamarin 工作并尝试使用一种方法使用所有服务。为此,我编写了一个 TaskExtension。这样我就可以从应用程序的每个页面调用该扩展方法。这是为了禁用按钮,显示加载屏幕,响应处理并从一个角度满足异常处理。我在下面附上我的代码。需要您对此解决方案的专家意见这是我的扩展类public static class TaskExtensions{    public static async Task<ResultViewModel<U>> ExecuteAsyncOperation<U>(this Task<HttpResponseMessage> operation, object sender = null)    {        ResultViewModel<U> resultModel = new ResultViewModel<U>();        Button button = BeforeAsyncCall(sender);        try        {            await BackgroundOperation(operation, resultModel);        }        catch (Exception ex)        {            resultModel.Status = HttpStatusCode.InternalServerError;            resultModel.Errors = new List<string>() { "Some error occurred. Please try again." };        }        finally        {            AfterAsyncCall(button);        }        return resultModel;    }    static async Task BackgroundOperation<U>(Task<HttpResponseMessage> operation, ResultViewModel<U> resultModel)    {        HttpResponseMessage RawResult = await operation;        var Response = await RawResult.Content.ReadAsStringAsync();        resultModel.Status = RawResult.StatusCode;        if (RawResult.IsSuccessStatusCode)        {            var responseObj = await Task.Run(() => JsonConvert.DeserializeObject<U>(Response));            resultModel.Result = responseObj;        }        else        {            var responseErrorObj = await Task.Run(() => JsonConvert.DeserializeObject<ErrorModel>(Response));            resultModel.Errors = new List<string>();            foreach (var modelState in responseErrorObj.ModelState)            {                foreach (var error in modelState.Value)                {                    resultModel.Errors.Add(error.ToString());                }            }        }    }
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 129 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信