Asynchronous delegates vs Threads

后端 未结 1 1889
执念已碎
执念已碎 2021-02-04 16:53

Replacing Threads (not ThreadPool Thread) with Asynchronous Delegates (Callbacks).

My Scenario: Spawn a Thread/del.beginInvoke() per Client.

According to me,

相关标签:
1条回答
  • 2021-02-04 17:57

    Your reasoning is correct. Async delegates use threads from the thread pool so they should be faster compared to manual thread creation. Be careful though with this in ASP.NET applications. Because you will be eating up worker threads that are normally used by ASP.NET to service requests and your application might very quickly run out of servicing capabilities.

    Async delegates are fine for CPU intensive tasks. For I/O intensive tasks (such as reading streams, database calls and web service calls) you should use the BeginXXX, EndXXX methods offered directly by the corresponding classes (Stream, SqlConnection, WebClient, ...). This way you are not using any threads at all during the lengthy I/O operation. You are using I/O Completion Ports which is the best thing in terms of I/O bound tasks. It will be orders of magnitude more performant and resource cheap than any threads and pools of threads.

    So to summarize:

    • For I/O intensive tasks use I/O Completion Ports. If the I/O intensive task is wrapped inside a poorly written library that doesn't offer this possibility use the TPL that was introduced in .NET 4.0.
    • For CPU intensive tasks use the TPL that was introduced in .NET 4.0.

    And if you don't have .NET 4.0 use thread pool unless you are writing an ASP.NET application in which case you might resort to manual thread creation.

    In general it is good practice to start using TPL and orient your methods as tasks so that you are ready for .NET 4.5 which introduces the async/await keywords.

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