1

私はタスクの初心者で、私の質問はばかげているかもしれませんが、本当に助けが必要です.

アプリの状態によりタスクをキャンセルしたい。

さて、ここに行きます:

    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 ステートメント内でコードを実行します。

私は間違いなく間違いを犯しており、上記の目標に到達するための正確な手順が必要です。

前もって感謝します。ジュリアン

4

1 に答える 1

0

私はあなたが次のようなものが必要だと思います:


while (!ct.IsCancellationRequested /* or all work is done*/)
{
    Console.WriteLine("DoSomeWork");
}
Console.WriteLine("We were cancelled.");
于 2012-05-17T14:45:34.130 に答える