Created
August 18, 2019 22:11
-
-
Save TheFo2sh/61702017642520395b130487076864a4 to your computer and use it in GitHub Desktop.
ShowProgressAttribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ShowProgressAttribute :MethodInterceptionAspect | |
{ | |
private string _title; | |
public ShowProgressAttribute(string title) | |
{ | |
_title = title; | |
} | |
public override async Task OnInvokeAsync(MethodInterceptionArgs args) | |
{ | |
var arguments = args.Arguments.ToList(); | |
var progressArg = args.Method.GetParameters() | |
.FirstOrDefault(a => typeof(IProgress<int>).IsAssignableFrom(a.ParameterType)); | |
if (progressArg != null) | |
{ | |
var progress=new Progress<int>(); | |
args.Arguments.SetArgument(args.Method.GetParameters().ToList().IndexOf(progressArg), progress); | |
var cancellationToken = new CancellationTokenSource(); | |
args.Arguments.SetArgument(arguments.IndexOf(args.Arguments.FirstOrDefault(a => a is CancellationToken)),cancellationToken.Token); | |
using (var dlg = UserDialogs.Instance.Progress(_title.Localize(), () => cancellationToken.Cancel(), null, true, maskType: MaskType.Black)) | |
{ | |
progress.ProgressChanged += (sender, i) => { Device.BeginInvokeOnMainThread((() => { dlg.PercentComplete = i; }); }; | |
try | |
{ | |
await args.ProceedAsync(); | |
} | |
catch (Exception ex) | |
{ | |
dlg.Hide(); | |
dlg.Dispose(); | |
throw ex; | |
} | |
} | |
} | |
else | |
{ | |
using (var dlg = UserDialogs.Instance.Loading(_title.Localize(), null, null, true, | |
maskType: MaskType.Black)) | |
{ | |
try | |
{ | |
await args.ProceedAsync(); | |
} | |
catch (Exception ex) | |
{ | |
dlg.Hide(); | |
dlg.Dispose(); | |
throw ex; | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment