Add code to current editor window in visual studio package/extention
How do you add/remove code in the code editor from an extension?
For example: I created an extension witch modifies the code from an incoming socket The example uses Microsoft.VisualStudio.Text.Editor
IWpfTextView textView; // got from visual studio "Create" event ITextChange change; // Got from network socket or other source
ITextEdit edit = textView.TextBuffer.CreateEdit(); // Throws "Not Owner" Exception edit.Delete(change.OldSpan); edit.Insert(change.NewPosition, change.NewText);
But I guess there's another way because the CrateEdit() Function fails
The problem here is that you are attempting to do an edit on an ITextBuffer from a different thread than the one that owns it. This is simply not possible. ITextBuffer instances are affinitized to a particular thread once the first edit occurs and after that point they cannot be edited from a different thread. The TakeThreadOwnership method will also fail after the ITextBuffer has been affinitized. Most other non-editing methods (CurrentSnapshot for example) can be called from any thread.
Typically an ITextBuffer will be affinitized to the Visual Studio UI thread. So to perform the edit use the original SynchronizationContext.Current instance or Dispatcher.CurrentDispatcher from the UI thread to get back onto the UI thread and then perform the edit.