I’m using a third-party richtextbox control, but I’m not very happy with the asynchronous loading of ‘.xaml’ files, so I tried this
async void LoadAsync(string str)
{
FileStream stream = File.OpenRead(str);
DocumentAdv? doc = await Task.Run(() => { return XamlReader.Load(stream) as DocumentAdv; });
RTB.Document.Dispatcher.Invoke(() =>
{
RTB.Document = doc;
});
}
But i got an expception——”The calling thread cannot access this object because a different thread owns it.”
What I’m trying to do is, since I don’t want to call its interface, I want to load the document asynchronously, and then assign it to my richtextbox control.
Why it happens and how do i fix it? Thx!
guangy ma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
I’m not familiar with the library you’re using, but the fundamental problem is that the document object is being constructed in a background thread as part of XamlReader.Load(stream)
, but then being assigned to RTB.Document
on the UI thread via the dispatcher.
If the amount of XAML data is truly considerable and you’re noticing a lag during the read from disk, then just use XamlReader.LoadAsync
instead. This will ensure that at least the disk read (where the biggest opportunity for delay exists) is asynchronous.
In no case should you need (or be able to) wrap any part of this in a Task.Run
. That will almost always lead to threading errors when you try to then apply what you did to the UI.
1