I'd like some ideas of how I can make a thread in C# to work as kind of an entity, where it stays "waiting" for me to call some method, and then that method will be executed inside that thread, and not on the thread that called the method.
Let me give an example:
public class ThreadClass
{
public void method1() { do something...}
public void method2() { do something...}
public void method3() { do something...}
} //my class with methods I want to run in another thread than UI, no order specific, when I need it...
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
//call method1, but it CANNOT RUN IN UI THREAD
}
private void button2_Click(object sender, EventArgs e)
{
//call method2, but it CANNOT RUN IN UI THREAD
}
} //main thread and class
To sum up: My thread has to live "forever", doing nothing, and when I click some button etc, some method will run inside it.
I've tried to use while loop, but I don't know how to call different methods in random moments.
CodePudding user response:
Microsoft's Reactive Framework has an EventLoopScheduler
class that does exactly what you want. NuGet System.Reactive
.
Try this:
void Main()
{
EventLoopScheduler els = new EventLoopScheduler(); //IDisposable
//starts a new thread and holds it until the instance is disposed.
IDisposable scheduled1 = els.Schedule(() => Method1());
IDisposable scheduled2 = els.Schedule(() => Method2());
IDisposable scheduled3 = els.Schedule(() => Method3());
//Once `Method1` completes `Method2` begins
//Once `Method2` completes `Method3` begins
IDisposable scheduled4 = els.ScheduleAsync((s, ct) => Method4Async(ct));
scheduled1.Dispose(); //Doesn't cancel if started, but unschedules
scheduled2.Dispose(); //Doesn't cancel if started, but unschedules
scheduled3.Dispose(); //Doesn't cancel if started, but unschedules
scheduled4.Dispose(); //Does cancel if started, if not unschedules
els.Dispose(); //Allows thread to end
}
public void Method1() { /* do something... */ }
public void Method2() { /* do something... */ }
public void Method3() { /* do something... */ }
public async Task Method4Async(CancellationToken ct) { /* do something... */ }
CodePudding user response:
public void SafeInvoke(Control control, Action action)
{
if (control.InvokeRequired)
control.Invoke(new MethodInvoker(() => { action(); }));
else
action();
}
Don`t forget set the CheckForIllegalCrossThreadCalls property to false