In diesem Code, wenn ich die Start-Funktion und danach mit einem gebundenen "Abbrechen" -Button starte, werde ich versuchen, die Aufgabe zu stoppen, er gab mir eine Ausnahme vom Typ "System.OperationCanceledException" sagen, dass nicht behandelt wurde im Benutzercode ...Warum throwIfCancellationRequested wird nicht in meinem try catch-Block behandelt?
Warum mein Versuch, Block zu fangen nicht damit umgehen? Wie kann ich diese Aufgabe über eine Schaltfläche "Abbrechen" in meiner Ansicht stoppen?
namespace LauncherWPF.ViewModel
{
/// <summary>
/// This class contLineageViewModel ains properties that a View can data bind to.
/// </summary>
public class : ViewModelBase
{
private CancellationTokenSource _tokenSource;
private CancellationToken _cancellationToken;
/// <summary>
/// Initializes a new instance of the LineageViewModel class.
/// </summary>
public LineageViewModel()
{
}
public void Start()
{
_tokenSource = new CancellationTokenSource();
_cancellationToken = _tokenSource.Token;
Debug.Write("TaskStarted");
try
{
Task.Run(() =>
{
for (var i = 0; i < 100; ++i)
{
_cancellationToken.ThrowIfCancellationRequested();
Debug.Write("Progress " + i);
for (var j = 0; j < 100; ++j)
{
Debug.Write("Updated " + j);
Thread.Sleep(50);
}
}
}, _cancellationToken);
}
catch (OperationCanceledException e)
{
Debug.Write("Canceled");
}
}
public void Cancel()
{
//not working
_tokenSource.Cancel();
}
}
}
Siehe auch https://stackoverflow.com/questions/28629405/exception-in-async-methods-is-not-caught –
Sorry, ich wusste nicht, dass mein Problem war mit der asynchronen Aufgabe verwandt, so war es nicht in der Lage, es mit dem richtigen Begriff zu suchen ... deshalb habe ich diese Frage erstellt. Fühlen Sie sich frei, es abzustimmen ... – exSnake