任务扩展以满足 App 范围的服务呼叫

Task Extension to Cater App Wide Service Calls

提问人:Safi Mustafa 提问时间:5/25/2018 最后编辑:Safi Mustafa 更新时间:6/4/2018 访问量:160

问:

我正在使用 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());
                }
            }
        }
    }
    static Button BeforeAsyncCall(object sender)
    {
        Button button = null;
        if (sender != null)
            button = (Button)sender;
        if (button != null)
            button.IsEnabled = false;
        UserDialogs.Instance.ShowLoading("Loading", MaskType.Black);
        return button;
    }
    static void AfterAsyncCall(Button button)
    {
        UserDialogs.Instance.HideLoading();
        if (button != null)
            button.IsEnabled = true;
    }
}

这是对我的扩展方法的调用

ResultViewModel<TokenModel> response = await new Service(Settings.BaseUrl).Login(loginModel).ExecuteAsyncOperation<TokenModel>(sender);

结果视图模型

public class ResultViewModel<T> 
    {
        public HttpStatusCode Status { get; set; }
        public T Result { get; set; }
        public List<string> Errors { get; set; }
    }

Async 方法

public async Task<HttpResponseMessage> Login(LoginViewModel loginModel)
        {
            try
            {

                var dataList = new List<KeyValuePair<string, string>>();
                dataList.Add(new KeyValuePair<string, string>("grant_type", "password"));
                dataList.Add(new KeyValuePair<string, string>("username", loginModel.Email));
                dataList.Add(new KeyValuePair<string, string>("password", loginModel.Password));
                var request = new HttpRequestMessage()
                {
                    RequestUri = new Uri(this.BaseUrl + "token"),
                    Method = HttpMethod.Post,
                    Content = new FormUrlEncodedContent(dataList)
                };
                var authenticateResponse = await Client.SendAsync(request);
                return authenticateResponse;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

我的问题是

1)这是一个好方法吗?

2)我们可以在性能方面改进它吗?

3) 我是否正确使用异步?

C# 泛型 xamarin xamarin.forms async-await

评论

0赞 rajwa766 5/28/2018
@Muhmmad奥马尔·阿斯拉姆(Omer Aslam)请看一看

答:

1赞 Alex Terry 5/30/2018 #1

1)这是一个好方法吗?

这种方法没有错。

2)我们可以在性能方面改进它吗?

使用扩展方法应该不会出现任何性能问题,但您可以 100% 确定。您正在使用 to 铸造创建装箱和拆箱情况。你能不能用.如果要支持多个元素类型,请使用。此外,使用 也有惩罚,但它们是最小的,并且对于不阻止 UI 是必要的。您可以通过添加任务来消除重新捕获上下文的需要来提高性能,但在这种情况下,您需要上下文来重新启用按钮。使用似乎没有必要,并且确实有一些开销。objectbuttonButtonViewElementasync await.ConfigureAwait(false)dynamic

3) 我是否正确使用异步?

如果该方法只返回一个 .您可以从调用方法中获取它。这将减少编译器的开销,并可能提高性能。不过,我以前没有测试过。awaitTaskTaskawait

外延

public static async Task<ResultViewModel<T>> ExecuteAsyncOperation<T>(this Task<HttpResponseMessage> operation, Button button)
{
    ResultViewModel<T> resultModel = new ResultViewModel<T>();
    try
    {
        if (button != null)
            button.IsEnabled = false;
        HttpResponseMessage RawResult = await operation;
        string Response = await RawResult.Content.ReadAsStringAsync();
        resultModel.Status = RawResult.StatusCode;

        if (RawResult.IsSuccessStatusCode)
        {
            var responseObj = JsonConvert.DeserializeObject<T>(Response);
            resultModel.Result = responseObj;
        }
        else
        {
            //create an error model instead of using dynamic I am guessing modelstate here
            List<ModelState> responseObj = JsonConvert.DeserializeObject<List<ModelState>>(Response);
            resultModel.Errors = new List<string>();
            foreach (ModelState modelState in responseObj)
            {
                foreach (var error in modelState.Errors)
                {
                    resultModel.Errors.Add(error.ToString());
                }
            }
        }
    }
    catch (Exception ex)
    {
        resultModel.Status = HttpStatusCode.InternalServerError;
        resultModel.Errors = new List<string>() { "Some error occurred. Please try again." };
    }
    finally
    {
        if (button != null)
            button.IsEnabled = true;
    }
    return resultModel;
}

var button = sender as Button; 
if (button != null)
{
    ResultViewModel<TokenModel> response = await new Service(Settings.BaseUrl).Login(loginModel).ExecuteAsyncOperation<TokenModel>(sender);
}

请求

public Task<HttpResponseMessage> Login(LoginViewModel loginModel)
{
    var dataList = new List<KeyValuePair<string, string>>();
    dataList.Add(new KeyValuePair<string, string>("grant_type", "password"));
    dataList.Add(new KeyValuePair<string, string>("username", loginModel.Email));
    dataList.Add(new KeyValuePair<string, string>("password", loginModel.Password));
    var request = new HttpRequestMessage()
    {
        RequestUri = new Uri(this.BaseUrl + "token"),
        Method = HttpMethod.Post,
        Content = new FormUrlEncodedContent(dataList)
    };
    return Client.SendAsync(request);
}

评论

0赞 Safi Mustafa 5/30/2018
我使用了动态,以便以后如果我需要返回HttpResponseMessage以外的其他内容,我可以。在这种情况下,我将使用 switch 语句。其次,我需要在调用每个方法之前强制转换按钮,为什么不在一个地方拆箱呢?最后,我读到应该一直使用 async 和 await。即使在 api 控制器中也是如此。您对此有何看法?
0赞 Safi Mustafa 5/30/2018
var responseErrorObj = JsonConvert.DeserializeObject<ErrorModel>(Response);.这里已经使用的模型忘记更新代码。
0赞 Safi Mustafa 5/30/2018
HttpResponseMessage RawResult = await operation;.无法执行此操作,因为它会导致编译时错误。无法将 T 隐式转换为 HttpResponseMessage
0赞 Safi Mustafa 5/30/2018
你说这不是一个坏方法。你能参考一些更好的方法吗?喜欢某个博客的链接吗?
0赞 Alex Terry 5/30/2018
您正在装箱和取消装箱两次,一次是在隐式强制转换时与事件一起,另一次是在调用方法并再次取消装箱时。您必须在某个地方为事件触发器开箱。您收到无法隐式转换 T 到 HttpResponseMessage 错误,因为我更改了要使用的方法签名,而不是避免使用 .我只指出了开销并给出了解决方案,如果它们不适合您的情况,那么您始终可以做出妥协。buttonTask<HttpResponseMessage>Task<T>dynamic