0

I have a web request (HttpRequest) which triggers a third library scanning method on my server that has an event handler attached to it:

scanner.OnScanComplete += scanner_OnScanComplete;

The web request will invoke scanner.Scan(files) but how can I force (or hook) the request to wait and get the results from scanner_OnScanComplete when the scan process is complete so it can return data to clients without having to send another web request to get this data?

void DoWork(HttpRequst request, var files)
{
 var scanner = new Scanner()
 scanner.OnScanComplete += scanner_OnScanComplete;
 scan(files)

}

void scanner_OnScanComplete(object sender, EventArgs e)
{

  var scanCompleted = true;

  //Return scanCompleted somehow to the DoWork thread above
}
Maya
  • 1,414
  • 5
  • 22
  • 43
  • This isn't real code so hard to help! `new Scanner` with no parenthesis?! How does `request` get used etc? What is `Scanner` and how does `OnScanComplete` work etc?! – Belogix Jun 29 '15 at 12:57
  • There is no real code, request is not being used, this is what im trying to figure out, i just put this as a an example to what i need to do why is this difficult to understand? – Maya Jun 29 '15 at 12:59
  • I added the parenthesis, now you can figure out what the code does? – Maya Jun 29 '15 at 13:03

2 Answers2

0

Do you have to use a HttpHandler or can you use other api's?

If you can use MVC4 or later then you can use an asynchronous Action Method to do this easily. Look here for an example of how to use them.

In addition to using an async Action Method you may need a way to await the event from the scanner. Using a Task Completion source as in this answer may be a good way to do that.

Community
  • 1
  • 1
Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76
0

One way to do what you want is to store the completion of the task in a boolean member. The boolean shall be marked volatile to avoid threading issues.

The risk of the approach is to lead to timeouts on client side if the scan processing is too long.

private volatile bool _finished;

void DoWork(HttpRequst request, var files)
{
    var scanner = new Scanner();
    scanner.OnScanComplete += scanner_OnScanComplete;

    _finished= false;
    scan(files)

    while (!_finished)    // wait for the scan completion
        System.Threading.Thread.Sleep(1000); // avoid consuming 100% cpu

    var scanData = Dothescanwork();
    //Return scanData somehow to the DoWork thread above
}

void scanner_OnScanComplete(object sender, EventArgs e)
{
    _finished= true; 
}
XouDo
  • 945
  • 10
  • 19
  • This will lock the thread that performs the request. While this is a possible option, it is not recommended. – Rune Grimstad Jun 29 '15 at 14:25
  • @RuneGrimstad It seems it's what she intended to do at first. No doubt there's a nicer way to do it. – XouDo Jun 30 '15 at 18:45