簡體   English   中英

C#在新線程中調用方法

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

我正在尋找一種在新線程上調用方法的方法(使用 C#)。

例如,我想在一個新線程上調用SecondFoo() 但是,我希望在SecondFoo()完成時終止線程。

我在C#看到了幾個線程的例子,但沒有一個適用於我需要生成的線程終止自身的特定場景。 這可能嗎?

如何強制運行Secondfoo()的生成線程在完成時終止?

有沒有人遇到過這樣的例子?

如果您實際啟動了一個新線程,則該線程在該方法完成時終止:

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

現在SecondFoo將在新線程中被調用,線程將在完成時終止。

真的是說你希望線程在調用線程中的方法完成時終止嗎?

編輯:請注意,啟動線程是一個相當昂貴的操作。 你肯定需要一個全新的線程而不是使用線程池線程嗎? 考慮使用ThreadPool.QueueUserWorkItem或(最好,如果您使用 .NET 4) TaskFactory.StartNew

它真的必須是一個線程,還是也可以是一個任務?

如果是這樣,最簡單的方法是:

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

一旦線程啟動,就沒有必要保留對 Thread 對象的引用。 線程繼續執行直到線程過程結束。

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

異步版本:

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

除非您有特殊情況需要非線程池線程,否則只需使用這樣的線程池線程:

Action secondFooAsync = new Action(SecondFoo);

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

      }), secondFooAsync); 

保證調用 EndInvoke 來為您處理清理工作。

據我了解,您需要將終止作為Thread.Abort()對嗎? 在這種情況下,您可以退出 Foo()。 或者您可以使用Process來捕獲線程。

Thread myThread = new Thread(DoWork);

myThread.Abort();

myThread.Start(); 

流程示例:

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