Non-blocking method call in C#: Use of ThreadPool.QueueUserWorkItem
and Task.Run
In C#, methods can be executed non-blockingly, allowing threads to continue executing without waiting for the method to complete.
The most direct way is to use the ThreadPool.QueueUserWorkItem
method. It accepts a WaitCallback
delegate as parameter, which specifies the method to be executed asynchronously.
Example:
<code class="language-csharp">using System.Threading; class Foo { static void Main() { // FireAway将在后台执行 ThreadPool.QueueUserWorkItem(o => FireAway()); Console.WriteLine("立即执行"); } static void FireAway() { Thread.Sleep(5000); Console.WriteLine("5秒后执行"); } }</code>
In this example, the FireAway
method is enqueued into the thread pool and the main thread continues execution immediately after initiating the asynchronous call.
Another method: Task.Run
A more modern and concise way to run tasks asynchronously is to use the Task.Run
method, which returns a Task
object representing the asynchronous operation.
Example:
<code class="language-csharp">using System.Threading.Tasks; class Foo { static void Main() { // FireAway将在后台执行 Task.Run(() => FireAway()); Console.WriteLine("立即执行"); } static void FireAway() { Thread.Sleep(5000); Console.WriteLine("5秒后执行"); } }</code>
ThreadPool.QueueUserWorkItem
and Task.Run
both provide efficient ways to execute methods non-blockingly in C#. However, when using these technologies in different scenarios, it is important to consider their potential impacts and limitations.
The above is the detailed content of How to Make Non-Blocking Method Calls in C# Using `ThreadPool.QueueUserWorkItem` and `Task.Run`?. For more information, please follow other related articles on the PHP Chinese website!