1

I have a function in the library that take in an Eventhandler as an input argument something like

public static void searchSth(string keyword, System.EventHandler callbackFunction)
{
    //do searching
    callbackFunction(null, null);
}

The searching result stored in the library public static class/variable

in my program, I would like to perform searching, and I have to call this function. based on the search result, I update my variable

while(!endSearch)
{
    //do something
    library.searchSth(keyword, new System.EventHandler(myEventHandler);
}

and I have also define my event handler

public void myEventHandler(object sender, EventArgs e)
{
    //update something based on the searching result
}

The problem is, my program didn't wait for the searching function to be finished. Instead it will just run continuously and catch in the infinite loop.

It makes sense that my program didn't wait because my program don't know when will the searching function is completed and when will it call the event handler function.

However, the endsearch condition is based on my searching result.

One solution is to use recursive function, and do all the stuff inside my event handler function

Is there better way that I can control my program flow?

Any suggestions would be appreciated

William
  • 11
  • 1
  • how are you updating endSearch variable? you should return a boolean out of your searchSth and assign it to your endSearch variable... or add out bool parameter to the function and pass endSearch to it so it gets updated eventually and get out of your loop. – Alejandro Mar 12 '20 at 03:09
  • there is a if statement inside the while loop, the condition is based on my variable, which would be updated inside the event handler function – William Mar 12 '20 at 03:16
  • No, I have no control to the code inside the library – William Mar 12 '20 at 03:16
  • You need to use some kind of monitor/semaphore/etc., set in your event handler, and waited on in the main thread. See marked duplicate. – Peter Duniho Mar 12 '20 at 03:33

0 Answers0