0

I'm using AvalonEdit since more than 2 years without problems and it work great
I'm just facing one issue on changing text from background thread
using SetOwnerThread() method trigger VerifyAccess() Exception every time even when called from main thread
If I do everything in the main thread it work but this also freeze the UI
It's why I want to do it in another thread and show a loading indicator to the user
I can't seem to understand what i'm doing wrong here
Any help or idea will be greatly apprecied
Thanks in advance

Edit:
I don't want to use Dispatcher.Invoke cause it will block the UI while updating

Sample code

public async void EditTextSample()
{
    Thread lUiThread = Thread.CurrentThread;

    //SelectedTab is the current tab viewed by the user in my application
    SelectedTab.TextEditor.Document.SetOwnerThread(null);

    await Task.Run(() => 
    {
        Thread lBackgroundThread = Thread.CurrentThread;

        SelectedTab.TextEditor.Document.SetOwnerThread(lBackgroundThread);

        string lNewText = ""
        SelectedTab.TextEditor.Document.Text = lNewText;

        SelectedTab.TextEditor.Document.SetOwnerThread(lUiThread);
    });
}

Some screenshots
https://i.stack.imgur.com/z0cee.jpg

  • You have to use `Dispatcher.Invoke` to update a controls from a different thread, like it's described here [Change WPF controls from a non-main thread using Dispatcher.Invoke](https://stackoverflow.com/questions/1644079/change-wpf-controls-from-a-non-main-thread-using-dispatcher-invoke) Also, please do not post code/errors as images – Pavel Anikhouski Jan 20 '20 at 18:54
  • Yes I Know when to use Dispatcher.Invoke, but here I don't want to because it will freeze the main UI will updating. Not enough rep to post image. I'm trying to use SetOwnerThread method to allow me to update this control from a background thread. – fredodiable Jan 20 '20 at 19:02
  • The UI thread must own the document while it's being displayed in an editor. Try creating a new document on the background thread, then updating the editor by setting textEditor.Document once the new document is loaded. – Daniel Feb 24 '20 at 13:06

1 Answers1

1

I'm back,
so as Daniel suggested creating a new TextDocument on the background thread did the trick
Note : This will reset the undo stack
Here is an example solution :)

public async void EditTextSample()
{
    Thread lUiThread = Thread.CurrentThread;

    //SelectedTab is the current tab viewed by the user in my application
    ITextSource lDocumentSnapshot = SelectedTab.TextEditor.Document.CreateSnapshot();
    TextDocument lNewDocument = null;

    await Task.Run(() => 
    {
        lNewDocument = new TextDocument();

        string lCurrentText = lDocumentSnapshot.Text;
        string lNewText = "";

        lNewDocument.Text = lNewText;

        lNewDocument.SetOwnerThread(lUiThread);
    });

    SelectedTab.TextEditor.Document = lNewDocument;
}