'Can we invoke method outside the thread block by any technique in C#? so that we can use same thread method to invoke other methods as well.?
e.g. Here in this example, if I want to start thread on method M1 this way, Purpose is I need to call M2, M3 on same thread method to avoid repeated code. Is this possible in C#?
static void Main()
{
if(StartThread() => M1()) //I want to invoke Method M1 from here like this
{
return;
}
}
private void StartThread()
{
var t = new Thread(() => M1()); //I dont want to invoke Method M1 from here
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
}
private static void M1()
{
throw new NotImplementedException();
}
Solution 1:[1]
Just use a delegate (e.g. an Action
) and pass it to StartThread
:
static void Main()
{
if(StartThread(() => M1()))
return;
}
private void StartThread(Action a)
{
var t = new Thread(() => a());
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
}
private static void M1()
{
throw new NotImplementedException();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | MakePeaceGreatAgain |