C#
 Computer >> コンピューター >  >> プログラミング >> C#

スレッドを強制終了するC#プログラム


最初にスレッドを作成して開始します-

// new thread
Thread thread = new Thread(c.display);
thread.Start();

次に、スレッドを表示し、停止機能を設定してスレッドの動作を停止します-

public void display() {
   while (!flag) {
      Console.WriteLine("It's Working");
      Thread.Sleep(2000);
   }
}
public void Stop() {
   flag = true;
   }
}

以下は、C#でスレッドを強制終了する方法を学習するための完全なコードです。

using System;
using System.Threading.Tasks;
using System.Threading;
class Demo {    
   static void Main(string[] args){
      MyClass c = new MyClass();      
      // new thread      
      Thread thread = new Thread(c.display);      
      thread.Start();      
      Console.WriteLine("Press any key to exit!");      
      Console.ReadKey();      
      c.Stop();      
       thread.Join();    
   }
}
public class MyClass {    
   private bool flag = false;    
   public void display() {      
      while (!flag) {        
         Console.WriteLine("It's Working");    
         Thread.Sleep(2000);      
       }    .
   }    .
   public void Stop() {      
      flag = true;    
   }
}
出力
It's Working
Press any key to exit!

  1. C#のバブルソートプログラム

    バブルソートは単純なソートアルゴリズムです。この並べ替えアルゴリズムは比較ベースのアルゴリズムであり、隣接する要素の各ペアが比較され、要素が順番に並んでいない場合は要素が交換されます。 intに5つの要素があるとしましょう- int[] arr = { 78, 55, 45, 98, 13 }; それでは、バブルソートを実行しましょう。 最初の2つの要素78と55から始めます。55は78より小さいので、両方を交換します。これでリストは-になります 55, 78,45,98, 13 現在、45は78未満なので、交換してください。 55, 45, 78, 98, 3 現在、98は78より大き

  2. 現在のスレッドのステータスをチェックするC#プログラム

    C#で現在のスレッドのステータスを確認するには、 IsAliveを使用します プロパティ。 まず、 currentThreadを使用します スレッドに関する情報を表示するプロパティ- Thread thread = Thread.CurrentThread; 次に、 thread.IsAliveを使用します スレッドのステータスをチェックするプロパティ- thread.IsAlive 例 C#で現在のスレッドのステータスを確認するための完全なコードを見てみましょう。 using System; using System.Threading; namespace Demo {