when form is loaded myMethod() is called and then it executes some statements. at some point when it gets to if statement it should stop and wait for user to press some button and then it will continue executing according to what user did. i used Thread.Sleep() and ManualResetEvent obj’s WaitOne() method but they seem to freeze the whole process nothing can be done until the time expires. I think that KeyEventHandler in should be run in background so it never feezzed… Anyway how can I do that ?
public partial class Form1 : Form
{
bool pressed = false;
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyDown +=new KeyEventHandler(Form1_KeyDown);
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.E)
{
pressed = true;
}
}
void myMethod()
{
while (someBool)
{
//do something
if (pressed)
//do this
else
//do that
}
}
private void Form1_Load(object sender, EventArgs e)
{
myMethod();
}
}
Try starting your method as a
Task:When you test for
pressedin your method, set it tofalse:Of course, this can potentially cause a variety of multithreading errors, depending on what you actually do in
myMethod(). I suggest that you look into thread synchronization before you start working with multiple threads.