Home > Backend Development > C++ > How to Make Non-Blocking Method Calls in C# Using `ThreadPool.QueueUserWorkItem` and `Task.Run`?

How to Make Non-Blocking Method Calls in C# Using `ThreadPool.QueueUserWorkItem` and `Task.Run`?

Patricia Arquette
Release: 2025-01-18 16:02:09
Original
974 people have browsed it

How to Make Non-Blocking Method Calls in C# Using `ThreadPool.QueueUserWorkItem` and `Task.Run`?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template