Search code examples
c#web-servicesasynchronousbackgroundworkerupdating

Alternative way to update status asynchronously than BackgroundWorker


I am working on some software that is making calculations on the server side. I have tried using BackgroundWorker and it was working perfectly fine until I tried switching from fat client to a web service. The error (which I was already expecting due to what my colleagues told me) "BackgroundWorker is not marked as Serializable" occured. The goal of my application is to update the client with the progress of the calculation as well as the name of the record currently being calculated. If needed I can post some code, but in this case I doubt it is really relevant to the problem. The scheme of what I am trying to achieve could be shown like this:

  • Client hits button "prepare"
  • Server gets the call
  • Server sends the data
  • Client receives the records list to confirm
  • Client confirms their choice (I then set up the background worker and send it to the server)
  • Server gets the call (receives the background worker's reference, as well as all the records needed to calculate at once)
  • With a loop I run through the records (each calculation takes ~1-3 seconds), update BackgroundWorker's status like this:

    worker.ReportProgress(i * 100 / ids.Length, "Currently counting: " + id + "...");
    Calculate(ids[i]);
    worker.ReportProgress((i+1) * 100 / ids.Length, "Currently counting: " + id + "...");
    

Is there any way to achieve what I am trying to to work also on the web service too? I assume it would require either tricking BackgroundWorker into Serializable or maybe there are other ways to update the status from the server to the client?

P.S. I am not sending very much data back from the server (I could actually even try to send even less data like id only), so I assume that won't be a problem of the overload.


Solution

  • Basically when you're writing code for the web, you're dealing with an entirely different model, based on request/response rather than continual interaction.

    You should probably make your initial request return a sort of "task ID" (which can be any unique ID), and return that quickly. Meanwhile, you start the task in the background. The client can then poll for the status of that particular task. You could use "long polling" where each request hangs around until there's a change in status, or just make the client call the server regularly. Either way, the response will just be the progress (the number of records processed and the name of the current record).