开发者

Wait for a button click inside foreach loop

I want to create in my application a logic showed below

foreach(item in collection)
{
   //do something...wait for a button click (pause until button is clicked)
   //after button is clicked do another thing 
}

After hours of googl开发者_开发知识库ing only one I know is that it can be handle with threads. I'm not familiar with this. If someone can explain issue it would be nice. I will appreciate any help

For your request let me explain more details

I want to compare the content in one of colums of DataTable object. Let say there are 10 rows in this column and in each row there is a differen word. I want to compare each word with the word put by user in TextBox control. The word of row 1 is displayed and user has to write it in text box. After put it in TextBox he must confirm it by clicking a button, and this will repeat 9 times.

foreach(DataRow dr in DataTab.Rows)<br/>
{
    string wordFromDB = dr["words"].ToString()
    //wait for a button click (pause until button is clicked)
    string wordFormTextBox = TextBox1.Text

    if( wordFormDB==wordFormTextBox)
    {
        Label1.Text="ok";
    }
    else
    {
        Label1.Text="nok";
    }
}

something like this. Of course if there is a different approach, I am interested in it.


This should be done in a separate thread because if you do it in the main thread you will basically kill the application. So you would start by declaring a synchronization event:

private static AutoResetEvent _wait = new AutoResetEvent(false);

and then queue a worker thread to do the job:

ThreadPool.QueueUserWorkItem(state =>
{
    foreach (item in (IEnumerable<Foo>)state)
    {
        // This will block the thread until the event is signaled
        _wait.WaitOne();

        // At this point the button was clicked => do something else
    }
}, collection);

And in the click of the button signal the event:

private void Button1_Click(object sender, EventArgs e)
{
    _wait.Set();
}

Remark: the foreach loop is a bit strange. I don't quite understand what you are trying to achieve with it.


Don't do that with threads. They are EVIL... Anyway, solving a problem as simple as this with something as complex and monstrous as threads is not good.

I would suggest to keep a variable, like lastItem, which will hold the index / key for the las item you went through. Then, when the button is clicked, call a function that will execute the needed action, increment the lastItem variable, and then repeat - wait for button click.

Another problem with your idea would be that it can potentially lead to an infinite loop - if the thread waiting for button click would somehow fail, your could would have NO idea, as it will be stuck in waiting for the press...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜