I’m working on a project about PDF rendering in the C# language. I convert each page of PDF file to Image and Adds it to a ObservableCollection with a new thread by the below code:
ThreadStart myThreadDelegate = new ThreadStart(DoWork);
myThread = new Thread(myThreadDelegate);
myThread.SetApartmentState(ApartmentState.STA);
void DoWork()
{
for (int i = 0; i < pdfFile.Pages.Count; i++)
{
PdfPage page=pdfFile.LoadPage(i);
myObservableCollection[i]=page;
}
}
then pass the custom item of myObservableCollection to another UserControl for render it but I got an exception:
The calling thread cannot access this object because a different
thread owns it.
I know if I use UI thread my problem could be solved but I want load pdf pages in the background and user doesn’t wait for loading all pages and this is possible with a new thread.
You can use threads but have to use the
Dispatcherto access UI elements. Only the part, where you pass the item to theUserControlhas to be done by the dispatcher.BeginInvokeis a asynchronous call and won’t block the execution of the following code.Edit: I’m still not 100% sure if I unterstood the whole idea of your application but made a small sample which demonstrates how you can use threads and UI elements.
I made a
Window(that would be yourUserControl) which contains aButtonand aListBox. When clicking theButtona thread is started and processes some items. In my case it just adds some texts into a list, I addedThread.Sleep(1000)to simulate the processing of lots of stuff. When the text is prepared, it will be added to theObservableCollection, which has to be done by the UI thread (Dispatcher). There is nothing blocking the UI but this adding and this is done very fast. You can also start multiple threads at the same time.This is the code-behind of the
Window(theWindowitsself just contains aButtonand aListBox):