0

C# でスレッドを作成するにはどうすればよいですか?

Javaでは、Runnableインターフェースを実装します

class MyThread implements Runnable{
public void run(){
//metthod
}

その後

MyThread mt = new MyThread;
Thread tt = new Thread(mt);
tt.start()

または、単に Thread クラスを拡張することもできます

class MyThread extends Thread{
public void run(){
//method body
}

その後

MyThread mt = new MyThread
mt.start();
4

1 に答える 1

6

いいえ、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
});

ご覧のとおり、一連のコードを別のスレッドで実行するために使用できるテクニックは無数にあります。

于 2012-12-26T13:53:01.410 に答える