-1

In my main class, I have a list of objects with a DateTime data member. I also have a method that loops through that list and checks its members against the current DateTime. I know I can use a Timer to call that method every interval. However, the method will be called very frequently (i.e. the interval is very short), and would block the user from doing anything else. I want the user to be able to interact with the form while the method is running in the background. However, if the method finds a match in its loop, I want the form to create another error-message form and stop anything else from happening until it's dealt with. What I need to know is how to get the method to be constantly called in the background, AND have it jump to the foreground and stop everything else if a specific thing happens.

Jacob
  • 207
  • 1
  • 9

3 Answers3

2

You can use a backgroundworker.

You can get the results on completion and you can also get results in the reports progress event.

paparazzo
  • 44,497
  • 23
  • 105
  • 176
0

You will have to use some form of Multitasking to do this.

As a beginner and working in Windows Forms, I usually advice for BackgroundWorker. That interuption is a bit tricky.

Working with the UI from another thread is really tricky, however. But I guess you could have the BGW's DoWork Event cancel (with an appropirate error message) and then display a modal Dialog (any form with ShowDialog() ) to block inputs from the RunWorkerCompleted Event.

Christopher
  • 9,634
  • 2
  • 17
  • 31
0

Asynchronous approach will help

private async Task DoJob()
{
    while (true) // or loop through DateTime values
    {
        await Task.Delay(1000): // 1 second
        if (DateTime.Now == dateTimeValue)
        {
            using (var form = new ErrorForm())
            {
                form.ShowDialog();
            }
        }

        // Possible condition for exit from while loop
    }
}

With async-await execution will remain on the main thread, which give you possibility to show error message without problems of accessing UI from different thread.

Fabio
  • 31,528
  • 4
  • 33
  • 72