私はタスクの初心者で、私の質問はばかげているかもしれませんが、本当に助けが必要です.
アプリの状態によりタスクをキャンセルしたい。
さて、ここに行きます:
static void Main(string[] args)
{
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
// Request cancellation from the UI thread.
if (Console.ReadKey().KeyChar == 'x')
{
tokenSource.Cancel();
}
Task.Factory.StartNew(() => DoSomeWork(token), token);
}
そしてここで DoSomeWork メソッド:
static void DoSomeWork(CancellationToken ct)
{
// Was cancellation already requested?
if (ct.IsCancellationRequested)
{
Console.WriteLine("We were cancelled before we got started.");
Console.WriteLine("DoSomeWork() - Not Executed");
return;
}
Console.WriteLine("DoSomeWork() - Executed");
Console.ReadLine();
}
したがって、tokenSource.Cancel(); を呼び出すと、それが期待されます。
この条件は true になります。
if (ct.IsCancellationRequested)
{
Console.WriteLine("We were cancelled before we got started.");
Console.WriteLine("DoSomeWork() - Not Executed");
return;
}
if ステートメント内でコードを実行します。
私は間違いなく間違いを犯しており、上記の目標に到達するための正確な手順が必要です。
前もって感謝します。ジュリアン