How to call a function in a backgroundworker thread that is to be completed on the main UI thread?

0

I am using a BackgroundWorker to monitor if a bit has flipped on an external device every couple of seconds. I then want it to call a function that is to be run on the main UI thread, but is instead being run on the same thread as the BackgroundWorker. This is a problem because I am getting errors about the application interface being marshaled on a different thread.

Currently when I call the function from the BackgroundWorker thread it is be computed on the same thread as the BackgroundWorker.

private void Task1()
{
    //Function does work before calling backgroundworker
    BackGroundWorker.RunWorkerAsync();
}

private async void BackGroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    //Monitor for bit being flipped on external device
    Task2();
}

private void Task2()
{
    //Work to be completed after the bit has been flipped
}

I'm expecting that once the bit has been detected to have flipped, the BackgroundWorker thread calls the function to be completed on the main UI thread.

What has actually been happening is that I get the following error because the function is being run on the same thread as the BackgroundWorker:

The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

c#
multithreading
uwp
backgroundworker
asked on Stack Overflow Aug 21, 2019 by Logan • edited Aug 21, 2019 by Peter Duniho

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0