简体   繁体   English

C#在新线程中调用方法

[英]C# Call a method in a new thread

I am looking for a way to call a method on a new thread (using C#).我正在寻找一种在新线程上调用方法的方法(使用 C#)。

For instance, I would like to call SecondFoo() on a new thread.例如,我想在一个新线程上调用SecondFoo() However, I would then like to have the thread terminated when SecondFoo() finishes.但是,我希望在SecondFoo()完成时终止线程。

I have seen several examples of threading in C# , but none that apply to this specific scenario where I need the spawned thread to terminate itself.我在C#看到了几个线程的例子,但没有一个适用于我需要生成的线程终止自身的特定场景。 Is this possible?这可能吗?

How can I force the spawned thread running Secondfoo() to terminate upon completion?如何强制运行Secondfoo()的生成线程在完成时终止?

Has anyone come across any examples of this?有没有人遇到过这样的例子?

If you actually start a new thread, that thread will terminate when the method finishes:如果您实际启动了一个新线程,则该线程在该方法完成时终止:

Thread thread = new Thread(SecondFoo);
thread.Start();

Now SecondFoo will be called in the new thread, and the thread will terminate when it completes.现在SecondFoo将在新线程中被调用,线程将在完成时终止。

Did you actually mean that you wanted the thread to terminate when the method in the calling thread completes?真的是说你希望线程在调用线程中的方法完成时终止吗?

EDIT: Note that starting a thread is a reasonably expensive operation.编辑:请注意,启动线程是一个相当昂贵的操作。 Do you definitely need a brand new thread rather than using a threadpool thread?你肯定需要一个全新的线程而不是使用线程池线程吗? Consider using ThreadPool.QueueUserWorkItem or (preferrably, if you're using .NET 4) TaskFactory.StartNew .考虑使用ThreadPool.QueueUserWorkItem或(最好,如果您使用 .NET 4) TaskFactory.StartNew

Does it really have to be a thread, or can it be a task too?它真的必须是一个线程,还是也可以是一个任务?

if so, the easiest way is:如果是这样,最简单的方法是:

Task.Factory.StartNew(() => SecondFoo())

Once a thread is started, it is not necessary to retain a reference to the Thread object.一旦线程启动,就没有必要保留对 Thread 对象的引用。 The thread continues to execute until the thread procedure ends.线程继续执行直到线程过程结束。

new Thread(new ThreadStart(SecondFoo)).Start();

Asynchronous version:异步版本:

private async Task DoAsync()
{
    await Task.Run(async () =>
    {
        //Do something awaitable here
    });
}

Unless you have a special situation that requires a non thread-pool thread, just use a thread pool thread like this:除非您有特殊情况需要非线程池线程,否则只需使用这样的线程池线程:

Action secondFooAsync = new Action(SecondFoo);

secondFooAsync.BeginInvoke(new AsyncCallback(result =>
      {
         (result.AsyncState as Action).EndInvoke(result); 

      }), secondFooAsync); 

Gaurantees that EndInvoke is called to take care of the clean up for you.保证调用 EndInvoke 来为您处理清理工作。

As far as I understand you need mean terminate as Thread.Abort() right?据我了解,您需要将终止作为Thread.Abort()对吗? In this case, you can just exit the Foo().在这种情况下,您可以退出 Foo()。 Or you can use Process to catch the thread.或者您可以使用Process来捕获线程。

Thread myThread = new Thread(DoWork);

myThread.Abort();

myThread.Start(); 

Process example:流程示例:

using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Threading;
using Microsoft.VisualBasic;

class PrintProcessClass
{

    private Process myProcess = new Process();
    private int elapsedTime;
    private bool eventHandled;

    // Print a file with any known extension.
    public void PrintDoc(string fileName)
    {

        elapsedTime = 0;
        eventHandled = false;

        try
        {
            // Start a process to print a file and raise an event when done.
            myProcess.StartInfo.FileName = fileName;
            myProcess.StartInfo.Verb = "Print";
            myProcess.StartInfo.CreateNoWindow = true;
            myProcess.EnableRaisingEvents = true;
            myProcess.Exited += new EventHandler(myProcess_Exited);
            myProcess.Start();

        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred trying to print \"{0}\":" + "\n" + ex.Message, fileName);
            return;
        }

        // Wait for Exited event, but not more than 30 seconds.
        const int SLEEP_AMOUNT = 100;
        while (!eventHandled)
        {
            elapsedTime += SLEEP_AMOUNT;
            if (elapsedTime > 30000)
            {
                break;
            }
            Thread.Sleep(SLEEP_AMOUNT);
        }
    }

    // Handle Exited event and display process information.
    private void myProcess_Exited(object sender, System.EventArgs e)
    {

        eventHandled = true;
        Console.WriteLine("Exit time:    {0}\r\n" +
            "Exit code:    {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);
    }

    public static void Main(string[] args)
    {

        // Verify that an argument has been entered.
        if (args.Length <= 0)
        {
            Console.WriteLine("Enter a file name.");
            return;
        }

        // Create the process and print the document.
        PrintProcessClass myPrintProcess = new PrintProcessClass();
        myPrintProcess.PrintDoc(args[0]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM