Task vs Asynchronous delegates in c#?

后端 未结 2 1782
长情又很酷
长情又很酷 2021-02-20 08:38

I have this simple method :

static int Work (string s) { return s.Length; }

I could run it with :

Task task =          


        
相关标签:
2条回答
  • 2021-02-20 09:04

    The second form, using IAsyncResult, is significantly older, and much less powerful. Task<T> was introduced in .NET 4, and is the preferred way of representing asynchronous operations now. It's much simpler to use, particularly in C# 5 which supports "asynchronous functions" where you can await a task (or other asynchronous operation) in a non-blocking way.

    Using a Task instead of calling BeginInvoke probably won't change much about how the operation itself is executed (although it gives you more options in terms of scheduling etc), but it makes a huge difference from the perspective of the code which wants to "watch" the operation, use the results, wait for multiple tasks, handle failures etc.

    If you can possibly use C# 5 (either with .NET 4.5, or with .NET 4 plus the async targeting pack) it will make your life considerably easier when it comes to managing asynchronous operations. It's the way forward :)

    0 讨论(0)
  • 2021-02-20 09:06

    Task is more elegant, and was introduced more recently (.Net 4) so if it meets your needs, I'd go with that.

    0 讨论(0)
提交回复
热议问题