I have a winforms application where I run a BackgroundWorker before the Application.Run
of the main Form.
When the BackgroundWorker is finished, in its RunWorkerCompleted
handler - it accesses the main Form, and I get the exception:
"Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on."
So I thought the error had to do with this comment which states that RunWorkerCompleted
"will only get raised on the UI thread if the UI thread created the BGW instance."
(though it doesn't seem like it's created on a separate thread). (And see this comment there too).
So I created a simple test where I BW.RunWorkerAsync();
before Application.Run
(In "Program") and it works fine there. No exception thrown.
So what might be the problem? Why does interacting with the main Form throw an exception though I am running the BackgroundWorker from the same thread?
(I can't post the whole code here because it's very long. And posting just the relevant code is what I mentioned earlier - it does not throw an exception.)
EDIT
So perhaps more concrete questions might be in place: How does one make the "UI thread create the BGW"? Does it have to be inside an Application.Run? After a Form is shown? Does it perhaps not depend on which thread created the BGW, but which thread calls RunWorkerAsync?
EDIT 2
Checking the Thread.CurrentThread.ManagedThreadId
I saw that it's 8 before RunWorkerAsync
(as it is before DoWork +=
and RunWorkerCompleted +=
) but 9 inside the RunWorkerCompleted
handler.
When stepping through the code and waiting after RunWorkerAsync()
for a couple of seconds - they all have the same thread ID and it runs fine consistently (so not just by chance that the correct thread was chosen)!