Why would I use async/await with Task.Run?

Is there a difference in this code?

public void Main()
{
  Console.Writeline("Foo");
  Task.Run(() => 
  {
    Console.Writeline("Bar");
  });
  Console.Writeline("Baz");
}

Or this?

public void Main()
{
  Console.Writeline("Foo");
  DoSomething();
  Console.Writeline("Baz");
}

public async void DoSomething()
{
   await Task.Run(() => 
   {
     Console.Writeline("Bar");
   });
}

I can’t figure out what is gained by using async/await with Task.Run, though CoPilot is telling me I should.

My goal is to find the “right” way to execute “fire and forget” code — code that needs to run, but that I don’t need to wait for.

7

Your first approach, with an ignored Task.Run, is called fire-and-forget. Any exception will be stored inside the task, but it will never be surfaced because you don’t .Wait() or await the task.

Your second approach, with an async void method, is called fire-and-crash. Any exception will be rethrown on the SynchronizationContext or TaskScheduler that was captured when the async void method started, which in this case is the ThreadPoolTaskScheduler. So the exception will be rethrown by a ThreadPool thread, causing the process to crash after raising the AppDomain.UnhandledException event.

Firstly, your two code blocks are functionally identical.

In the example you have given, as you don’t await DoSomething() then you can’t (easily) know if it succeeded, completed, faulted or for that matter even began.

If you are happy with this constraint then it’s absolutely fine to have what’s known as a Fire and Forget task.

Calling await will provide you with fault information.

Take the following example:

    static async Task Main(string[] args)
    {
        try
        {
            Console.WriteLine("Foo");
            var dt = DoSomething();  // Fire and forget
            Console.WriteLine("Baz");
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
        catch{
            Console.WriteLine("A fault occured");
        }

    }

    static async Task DoSomething()
    {
        await Task.Run(() =>
        {
            throw new Exception("My error");
        });
    }

The exception raised by DoSomething() will not be captured.

As opposed to:

    static async Task Main(string[] args)
    {
        try
        {
            Console.WriteLine("Foo");
            var dt = DoSomething();
            Console.WriteLine("Baz");
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
            await dt; // Check if the Task has finished
        }
        catch{
            Console.WriteLine("A fault occured");
        }

    }

    static async Task DoSomething()
    {
        await Task.Run(() =>
        {
            throw new Exception("My error");
        });
    }

Which will capture the exception at await dt; and allow you to take the necessary action.

As for your long running Task question. You can Fire and Forget, but you can’t really ever Forget.

Here’s an example you can try:

    static async Task Main(string[] args)
    {
        try
        {
            using CancellationTokenSource cts = new CancellationTokenSource();
            var task1 = FireAndForget(cts.Token);

            Console.WriteLine("Fire forget Task is running....press ENTER to exit");
            Console.ReadLine();

            // Uncomment these two lines
            // cts.Cancel();
            // await task1;

        }
        catch (OperationCanceledException)
        {
            // If the above are uncommented then the task terminated
            Console.WriteLine("Task was cancelled");
        }
        catch (Exception) { throw; }

        // If the above lines are still commented, the task will terminate here
        // when the main process terminates
    }

    static async Task FireAndForget(CancellationToken ct)
    {
        await Task.Run(() =>
        {
            while (true) // Background long running task
            {
                ct.ThrowIfCancellationRequested();
            }
        }, CancellationToken.None);
    }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật