How to check if document is under write action?
已回答
Hi,
I'm using CodeSmellDetecor in my document listener and whenever I try get code smells, it says "Must not run under write action". How can I check if document/file is currently under write action?
Thanks,
Alex
请先登录再写评论。
Check for null returned from getFile() just in case.
I think this would test if it is writeable. Not sure about it being under write action by someone else.
Thanks, isWritable() returns true, however still throws must not run in write action exception. The document is indeed at this moment being updated using WriteCommandAction.runWriteCommandAction(), however I want the document listener to run when the user is editing the document, thus ignore the case where the document is under a write action.
>How can I check if document/file is currently under write action?
"Write action" is a global lock, rather than a document state, see https://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/general_threading_rules.html
Most events in DocumentListener are fired in write action (exclusion is rare Documents, that are explicitly allowed on creation to ignore general threading rules).
If you perform any slow operations here, it will be perceived as "UI freeze"/"slow typing" by user. Thus, it should be avoided.
Alex, it is best in these cases to note the event and process it later using read action or by delayed Swing Alarm or any other mechanism which would allow the document write actions to complete before trying to do anything else.
Sometimes the simplest if not the cleanest approach is to wrap your code in ApplicationManager.getApplication().invokeLater() if your code can be executed in the AWT (Swing UI) thread and won't cause long UI response delays.
I usually try the invokeLater as a quick test to see if that is the only issue with the code.
Ah ok, so it isn't possible to call CodeSmellDetector.findCodeSmells() from within DocumentListener, unless it is from rare document which can ignore threading rules?
Yes.
But you shouldn't think about such weird documents (unless you've created one yourself).
Also, I'd suggest using background threads over "invokeLater" for the same reason (long operation in UI thread -> UI is frozen -> IDE is unresponsive).
See `com.intellij.openapi.application.ApplicationManager.getApplication()` / `Application.executeOnPooledThread` / `Application.runReadAction`.
See also `com.intellij.openapi.progress.Task.Modal` / `Task.Backgroundable` for modal/background progresses with visible indicators.
OK, thanks a lot