如何使异步任务在后台运行?

时间:2020-07-23 16:10:12

标签: c# asynchronous async-await console-application

我有TaskCompletionSource的这段代码。我需要在控制台应用程序中使用。但是关键是它应该在后台完成。如果我现在使用await queries.MarkRandomTaskWithDelay(1000),它将等待1000毫秒,然后我就可以继续使用该应用了。但是我需要立即继续工作,然后才能获得结果。我该怎么办?

public static class queries
{
    public static TaskCompletionSource<int> completionSource = new TaskCompletionSource<int>();

    public static Task<int> MarkRandomTaskWithDelay(int interval)
    {
        Timer timer = new Timer(interval)
        {
            AutoReset = false
        };

        timer.Elapsed += Marking;

        timer.Start();
        return completionSource.Task;
    }

    private async static void Marking(object o, ElapsedEventArgs e)
    {
        try
        {
            await SomeWork();

            Console.WriteLine($"\nTask status with ID {task.Id} was changed to 'finished' in background.\n");
            completionSource.SetResult(task.Id);
        }
        catch (Exception ex)
        {
            completionSource.SetException(ex);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在实际需要结果之前,不要使用await

//Start the task but don't wait for it to finish
Task<int> task = queries.MarkRandomTaskWithDelay(1000);

//Do whatever work we can do without knowing the result
DoOtherWork();
 
//Now we need the result, so we await the original task
int result = await task;
UseTheResult(result);