2011-11-04 10 views
27

(C#を使用して)新しいスレッドでメソッドを呼び出す方法を探しています。 たとえば、新しいスレッドでSecondFoo()に電話したいと思います。しかし、私はSecondFoo()が終了したらスレッドを終了させたいと思うでしょう。C#新しいスレッドでメソッドを呼び出す

C#にいくつかのスレッドの例がありますが、この特定のシナリオには該当しません。私はそれ自身を終了するために生成されたスレッドが必要です。これは可能ですか?

実行時に生成されたスレッドSecondfoo()を強制的に強制終了できますか?

誰もがこの例を見つけましたか?

多くのおかげで、 ブレット

+3

Secondfoo()が戻ると、実行中のスレッドは終了します。なぜそれはないと思いますか? –

+0

ThreadPoolを使用できない理由はありますか? –

答えて

61

あなたが実際に新しいスレッドを起動した場合はこの方法が終了すると、そのスレッド終了します:

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

SecondFooは新しいスレッドで呼び出され、スレッドは完了すると終了します。もし実際にあなたは呼び出しスレッドでメソッドが完了したときに終了するようにスレッドを望んでいたことを

を意味しましたか?

EDIT:スレッドを開始するのはかなりコストがかかることに注意してください。スレッドプールスレッドを使用するのではなく、新しいスレッドが必要ですか? ThreadPool.QueueUserWorkItemまたは(好ましくは.NET 4を使用している場合)TaskFactory.StartNewの使用を検討してください。

+1

これはそれです:-)実行するステートメントがなくなったときにスレッドが終了することを知らなかった。これは私が必要としていた正確な答えです。どうもありがとう!!! – Brett

41

本当にスレッドでなければならないのでしょうか、それともタスクでもありますか?

そうならば、最も簡単な方法は次のとおりです。

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

または単に 'Task.Run' – Omu

1

あなたは非スレッド・プールのスレッドを必要とする特殊な状況がある場合を除き、ちょうどこのようなスレッドプールのスレッドを使用します。

Action secondFooAsync = new Action(SecondFoo); 

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

     }), secondFooAsync); 

EndInvokeのGauranteesは、あなたのためにクリーンアップを世話するために呼び出されます。

+0

新しいスレッドで長い処理レポートを実行する前に、beginInvokeを使用しました。ここにBeginInvokeのMSDN記事があります:http://msdn.microsoft.com/en-us/library/2e08f6yc%28v=vs.71%29.aspx – William

+3

'ThreadPool.QueueUserWorkItem'を呼び出す方が簡単です... –

-2

私の知る限り、平均は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]); 
    } 
} 
4

は、スレッドプールで管理されています!このコードを考えてみましょう。

new Thread(new ThreadStart(SecondFoo)).Start(); 
関連する問題