每次调用特定方法时创建一个新的后台线程

发布于 2024-10-21 21:00:10 字数 208 浏览 1 评论 0原文

WinForm: 我的 MainApplication 中有一个名为 check_news 的方法。 如何创建并运行一个线程,每次调用该方法时(通过按按钮或在程序启动时),该线程都会在后台处理该方法?

我知道如何创建一个线程,但是每次调用该函数时如何创建新线程(新线程因为旧线程已死)?

我应该创建一个新类并使用新类对象和我需要的方法运行线程吗? 我应该在哪里定义线程?

WinForm:
I have a method called check_news in my MainApplication.
How can I create and run a Thread that will work on the method on background each time I call the method (by pushing a button, or in the start of the program)?

I know how to create a thread but how can I create new thread every time I call the function (new thread because the old one is dead)?

Should I create a new class and run the thread with the new class object and the method I need?
Where should I define the thread?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千寻… 2024-10-28 21:00:10
    public void Example()
    {
        //call using a thread.
        ThreadPool.QueueUserWorkItem(p => check_news("title", "news message"));
    }

    private void check_news(string news, string newsMessage)
    {

    }
    public void Example()
    {
        //call using a thread.
        ThreadPool.QueueUserWorkItem(p => check_news("title", "news message"));
    }

    private void check_news(string news, string newsMessage)
    {

    }
红玫瑰 2024-10-28 21:00:10

您可以通过编写 new Thread(...) 在方法内创建一个线程。
... 可以是方法名称、委托实例或匿名方法。

每次执行此代码时,都会创建一个新的 Thread 实例。

请注意,使用ThreadPool 会更高效。

You can just create a thread inside the method by writing new Thread(...).
The ... can be a method name, delegate instance, or anonymous method.

Each time this code executes, it will create a new Thread instance.

Note that it will be more efficient to use the ThreadPool instead.

金兰素衣 2024-10-28 21:00:10

我认为实现这一点的最佳方法是将其添加到线程池中,它既简单又快速。

示例:

public static void Main(string[] args)
{
    check_news();
}

private static void check_news()
{
    ThreadPool.QueueUserWorkItem((obj) =>
        {
            // Fetch the news here
            Thread.Sleep(1000); // Dummy
        });
}

或者,如果您确实想自己处理它,则可以使用以下内容:

public static void Main(string[] args)
{
    check_news();
    Console.ReadKey();
}

private static void check_news()
{
    Thread t = new Thread(() =>
        {
            // Check news here
            Thread.Sleep(1000); // Dummy
        });
    t.Priority = ThreadPriority.Lowest; // Priority of the thread
    t.IsBackground = true; // Set it as background (allows you to stop the application while news is fetching
    t.Name = "News checker"; // Make it recognizable
    t.Start(); // And start it
}

但您应该知道,这需要更长的时间来启动,它不会重用线程,并且没有真正的优势。

或者,如果您想要更多控制,可以使用异步平台:

public static void Main(string[] args)
{
    check_news(); // You can add an argument 'false' to stop it from executing async
    Console.WriteLine("Done");
    Console.ReadKey();
}

public delegate void Func();

public static void check_news(bool async = true)
{
    Func checkNewsFunction = () =>
        {
            //Check news here
            Thread.Sleep(1000);
        };
    if (async)
    {
        AsyncCallback callbackFunction = ar =>
        {
            // Executed when the news is received

        };
        checkNewsFunction.BeginInvoke(callbackFunction, null);
    }
    else
        checkNewsFunction();
}

请注意,所有示例中的 lambda 表达式也可以替换为常规函数。但我现在就使用它们,因为作为例子看起来更好。

I suppose the best way to achieve this is by adding it to the thread pool, it's easy and quick.

Example:

public static void Main(string[] args)
{
    check_news();
}

private static void check_news()
{
    ThreadPool.QueueUserWorkItem((obj) =>
        {
            // Fetch the news here
            Thread.Sleep(1000); // Dummy
        });
}

Or if you really want to deal with it yourself, this is something you could use:

public static void Main(string[] args)
{
    check_news();
    Console.ReadKey();
}

private static void check_news()
{
    Thread t = new Thread(() =>
        {
            // Check news here
            Thread.Sleep(1000); // Dummy
        });
    t.Priority = ThreadPriority.Lowest; // Priority of the thread
    t.IsBackground = true; // Set it as background (allows you to stop the application while news is fetching
    t.Name = "News checker"; // Make it recognizable
    t.Start(); // And start it
}

But you should know that this takes a longer time to start, it doesn't reuse threads, and there's not a real advantage in it.

Or if you want more control you could use the async platform:

public static void Main(string[] args)
{
    check_news(); // You can add an argument 'false' to stop it from executing async
    Console.WriteLine("Done");
    Console.ReadKey();
}

public delegate void Func();

public static void check_news(bool async = true)
{
    Func checkNewsFunction = () =>
        {
            //Check news here
            Thread.Sleep(1000);
        };
    if (async)
    {
        AsyncCallback callbackFunction = ar =>
        {
            // Executed when the news is received

        };
        checkNewsFunction.BeginInvoke(callbackFunction, null);
    }
    else
        checkNewsFunction();
}

Note that the lambda expressions in all examples can just as well be replaced by regular functions. But I just use them right now, because it seems nicer as example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文