オブジェクトを別のオブジェクトに渡す必要があります。c
に渡さなければならないことはわかっていt1
ます。どうすればいいですか
Thread t = new Thread(t1);
t.Start();
private static void t1(Class1 c)
{
while (c.process_done == false)
{
Console.Write(".");
Thread.Sleep(1000);
}
}
オブジェクトを別のオブジェクトに渡す必要があります。c
に渡さなければならないことはわかっていt1
ます。どうすればいいですか
Thread t = new Thread(t1);
t.Start();
private static void t1(Class1 c)
{
while (c.process_done == false)
{
Console.Write(".");
Thread.Sleep(1000);
}
}
あなたは単に行うことができます:
Thread t = new Thread(new ParameterizedThreadStart(t1));
t.Start(new Class1());
public static void t1(object c)
{
Class1 class1 = (Class1)c;
...
}
MSDN: ParameterizedThreadStart デリゲート
またはさらに良い:
Thread thread = new Thread(() => t1(new Class1()));
public static void t1(Class1 c)
{
// no need to cast the object here.
...
}
このアプローチでは複数の引数が許可され、オブジェクトを目的のクラス/構造体にキャストする必要はありません。
皆さん、オブジェクトがスレッドの外でも使用されているという点を誰もが見逃しています。このようにして、クロススレッド例外を回避するために同期する必要があります。
したがって、解決策は次のようになります。
//This is your MAIN thread
Thread t = new Thread(new ParameterizedThreadStart(t1));
t.Start(new Class1());
//...
lock(c)
{
c.magic_is_done = true;
}
//...
public static void t1(Class1 c)
{
//this is your SECOND thread
bool stop = false;
do
{
Console.Write(".");
Thread.Sleep(1000);
lock(c)
{
stop = c.magic_is_done;
}
while(!stop)
}
}
お役に立てれば。
よろしく
private static void DoSomething()
{
Class1 whatYouWant = new Class1();
Thread thread = new Thread(DoSomethingAsync);
thread.Start(whatYouWant);
}
private static void DoSomethingAsync(object parameter)
{
Class1 whatYouWant = parameter as Class1;
}