Search code examples
c#foreachtimermanualresetevent

Timer in foreach with ManualResetEvent


When I click the button, the cycle starts to read the database and send each row of the query to another server. When get response - the cycle continues.

Code is implemented as follows

private ManualResetEvent _mre = new ManualResetEvent(true);

and

Thread startUpload = new Thread(() =>
{
   //read database

   foreach (DataRow dr in dt.Rows)
      {

         //send request

         _mre.WaitOne();
      }
});

startUpload.Start();

The problem is that when requests are sent may not be the answer. In my case this is normal. But if not, the answer comes, then the cycle stops. I need to do inside the loop timer, which in the case of stopping the cycle due to lack of response will continue to cycle in 30 seconds.

The timer will have to do

_mre.Set();

Solution

  • IMPORTANT: You're setting your ManualResetEvent initial state to true, set it to false if you're willing to stop current process and wait for signal.

    EDIT:

    Example

    private ManualResetEvent _mre = new ManualResetEvent(false);
    
    private void ReadTheDatabase()
    {
        Thread startUpload = new Thread(() =>
        {
            // Read the data
    
            foreach (DataRow dr in dt.Rows)
            {
                // Send request
                Thread requestMethod = new Thread(() =>
                {
                    // Imitate process with thread sleep
                    Thread.Sleep(5000);
                    _mre.Set();
                });
    
                requestMethod.Start();
    
                _mre.WaitOne(30000, false);
            }
        });
    
        startUpload.Start();
    }