How to pass LongRunning flag specifically to Task.Run()?

前端 未结 6 1842
抹茶落季
抹茶落季 2020-12-14 17:31

I need a way to set an async task as long running without using Task.Factory.StartNew(...) and instead using Task.Run(...) or something similar.

Context:

I h

6条回答
  •  感情败类
    2020-12-14 17:39

    Call Unwrap on the task returned from Task.Factory.StartNew this will return the inner task, which has the correct status.

    var cts = new CancellationTokenSource();
    Task t = Task.Factory.StartNew(
    async () => {
    while (true)
    {
        cts.Token.ThrowIfCancellationRequested();
        try
        {
            "Running...".Dump();
            await Task.Delay(500, cts.Token);
        }
        catch (TaskCanceledException ex) { }
    } }, cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default).Unwrap();
    

提交回复
热议问题