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

前端 未结 6 1854
抹茶落季
抹茶落季 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:58

    On a dedicated thread, there's nothing to yield to. Don't use async and await, use synchronous calls.

    This question gives two ways to do a cancellable sleep without await:

    Task.Delay(500, cts.Token).Wait(); // requires .NET 4.5
    
    cts.WaitHandle.WaitOne(TimeSpan.FromMilliseconds(500)); // valid in .NET 4.0 and later
    

    If part of your work does use parallelism, you can start parallel tasks, saving those into an array, and use Task.WaitAny on the Task[]. Still no use for await in the main thread procedure.

提交回复
热议问题