Search code examples
c#backgroundworker

C# BackgroundWorker running HTTP Server, modifying contols on the host thread's form


This one is a tough one...

I've got a C# app that runs an HTTP server in a BackgroundWorker, it allows users to input data, that should display in real time onto a main form. The HTTP server basically runs in a do/while(true) loop, that always waits for the HTTP response. So it has to run in a BackgroundWorker so that the program does not stop responding while waiting for the web user. However, when the user enters data, I want the background worker to update the data on the main form.

I've tried making the functions of the main form public, but this gives a run time exception because the thread accessing the forms controls is not the thread that created them.

I've thought about just using the ProgressChanged event of the BW, but I've got to pass a lot of data, and it would be nicer to pass more than just a string. Can I override this method, and if I can, how/where would I do it??

Thanks.


Solution

  • Go ahead and use ProgressChanged as-is. It doesn't really matter how big the object you're passing as the userState parameter is, as long as:

    • It's a reference type (that is, not a struct).
    • The background process doesn't modify its contents after passing back to the main thread, to avoid a race condition.