Add cancellation logic to preview

This commit is contained in:
Frank A. Krueger 2017-12-10 20:37:16 -08:00
parent f0ed625159
commit 0203e3c4b8
1 changed files with 16 additions and 2 deletions

View File

@ -1,6 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading;
using Xamarin.Forms; using Xamarin.Forms;
namespace Samples namespace Samples
@ -37,19 +37,33 @@ namespace Samples
DisplayXaml (); DisplayXaml ();
} }
CancellationTokenSource lastCts = null;
public void DisplayXaml () public void DisplayXaml ()
{ {
try { try {
var cts = new CancellationTokenSource ();
var token = cts.Token;
lastCts?.Cancel ();
lastCts = cts;
var asm = typeof (Xamarin.Forms.Xaml.Internals.XamlTypeResolver).Assembly; var asm = typeof (Xamarin.Forms.Xaml.Internals.XamlTypeResolver).Assembly;
var xamlLoaderType = asm.GetType ("Xamarin.Forms.Xaml.XamlLoader"); var xamlLoaderType = asm.GetType ("Xamarin.Forms.Xaml.XamlLoader");
var loadArgTypes = new[] { typeof (object), typeof (string) }; var loadArgTypes = new[] { typeof (object), typeof (string) };
var loadMethod = xamlLoaderType.GetMethod ("Load", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public, null, System.Reflection.CallingConventions.Any, loadArgTypes, null); var loadMethod = xamlLoaderType.GetMethod ("Load", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public, null, System.Reflection.CallingConventions.Any, loadArgTypes, null);
var contentView = new ContentView (); var contentView = new ContentView ();
loadMethod.Invoke (null, new object[] { contentView, editor.Text }); loadMethod.Invoke (null, new object[] { contentView, editor.Text });
if (!token.IsCancellationRequested) {
results.Content = contentView; results.Content = contentView;
} }
}
catch (OperationCanceledException) {
}
catch (Exception ex) { catch (Exception ex) {
results.Content = new Label { results.Content = new Label {
TextColor = Color.DarkRed,
FontSize = 12,
Text = ex.ToString (), Text = ex.ToString (),
}; };
} }