AvalonEdit Change owner thread

246 views Asked by At

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

1

There are 1 answers

0
fredodiable On BEST ANSWER

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;
}