いいえ、Java とは異なり、.NET ではThreadクラスを拡張できません。これは、封印されているためです。
したがって、新しいスレッドで関数を実行する最も単純な方法は、手動で新しいスレッドを生成し、実行する関数を渡すことです (この場合は無名関数として)。
Thread thread = new Thread(() =>
{
// put the code here that you want to be executed in a new thread
});
thread.Start();
または、匿名デリゲートを使用したくない場合は、メソッドを定義します。
public void SomeMethod()
{
// put the code here that you want to be executed in a new thread
}
次に、同じクラス内で、このメソッドへの参照を渡す新しいスレッドを開始します。
Thread thread = new Thread(SomeMethod);
thread.Start();
メソッドにパラメーターを渡したい場合は、次のようにします。
public void SomeMethod(object someParameter)
{
// put the code here that you want to be executed in a new thread
}
その後:
Thread thread = new Thread(SomeMethod);
thread.Start("this is some value");
これは、バックグラウンド スレッドでタスクを実行するネイティブな方法です。新しいスレッドを作成するための高額な支払いを避けるために、ThreadPoolのスレッドの 1 つを使用できます。
ThreadPool.QueueUserWorkItem(() =>
{
// put the code here that you want to be executed in a new thread
});
または非同期デリゲート実行を使用する:
Action someMethod = () =>
{
// put the code here that you want to be executed in a new thread
};
someMethod.BeginInvoke(ar =>
{
((Action)ar.AsyncState).EndInvoke(ar);
}, someMethod);
このようなタスクを実行するためのさらに別のより現代的な方法は、TPL を使用することです (.NET 4.0 以降)。
Task.Factory.StartNew(() =>
{
// put the code here that you want to be executed in a new thread
});
ご覧のとおり、一連のコードを別のスレッドで実行するために使用できるテクニックは無数にあります。