控制台应用程序中的异步任务/线程

时间:2014-01-26 20:04:45

标签: c# multithreading asynchronous console task

是否可以运行Task或启动Thread异步?我想做的简短例子:

public static void Main () {
    // Code

    Task.Run(() => {
        // WebRequest that works asynchron to console
        // I don't need to output results
    });

    // Code

    // Console shouldn't close until Task finished
}

1 个答案:

答案 0 :(得分:2)

您可以在Task.Wait()

的结果上致电Task.Run()
Task t = Task.Run(() =>
{
    Thread.Sleep(1000);
    Console.WriteLine("Task is about to exit");
});

Console.WriteLine("Now waiting for the task to exit...");
t.Wait();