首页 > 学院 > 开发设计 > 正文

Intellij插件开发:MonkeyMaster插件的实现(三)——写入日志的线程处理

2019-11-08 00:35:53
字体:
来源:转载
供稿:网友

【转载请注明出处】 笔者:DrkCore (http://blog.csdn.net/DrkCore) 原文链接:(http://blog.csdn.net/drkcore/article/details/56680079)

一、 插件开发中的线程问题

我想大部分从事过Android开发的朋友在第一次在IntelliJ Idea插件开发文档中看到关于线程使用规范时,都会像笔者一样困惑不已:

IntelliJ Platform SDK DevGuide: General Threading Rules

Reading data is allowed from any thread. Reading data from the UI thread does not require any special effort. However, read Operations performed from any other thread need to be wrapped in a read action by using applicationManager.getApplication().runReadAction() or, shorter, ReadAction.run/compute.

允许在任意线程读取数据。从UI线程中读取数据并不要求任何额外的操作,但在其他线程你需要将读取的逻辑包裹在 ApplicationManager.getApplication().runReadAction()中才行,你也可以使用 ReadAction.run/compute 来简化代码。

Writing data is only allowed from the UI thread, and write operations always need to be wrapped in a write action with ApplicationManager.getApplication().runWriteAction() or, shorter, WriteAction.run/compute

只允许在UI线程写入数据,并且写入数据的逻辑必须包裹在 ApplicationManager.getApplication().runWriteAction() 才能执行,你也可以使用 WriteAction.run/compute 来简化你的代码。

“不要在主线程中执行耗时的操作”是我们在开发Android应用时应当牢记的准则。在Intellij Idea插件开发中显然不是这样的,按照文档我们就该将写入这样的耗时操作放在UI线程,饶是如此,如果你一个写入操作执行的时间太长UI照样是会卡主的。

这里就会有一个问题:

Monkey测试的事件是随机的要想测出问题就要花费大量的时间,并且日志通常很大。有不少同行都喜欢下班前执行一次超长的测试任务,第二天上班再查看日志。要是直接在UI线程中执行操作的话有可能会把整个Intellij Idea都卡主了。

将日志保存到内存中待任务结束后再一次性写入磁盘是可以解决问题,但是一旦中途发生了异常就有可能导致日志丢失,并且运行时你无法查看日志文件。当然我们也可以设计成每输出比如10K大小的日志数据时就执行一次保存操作,但开发起来就会比较纠结。

有没有好点的解决方案呢?当然有!

熟悉命令行的朋友应该知道我们可以将命令行的输出通过 > 符号保存到指定的文件中去,该方法对 Win / linux / os X 都是有效的。按照官方文档我们可以在任何线程执行读取操作,因此我们只要新开一个线程用于读取日志文件接口即可。是不是忽然觉得这个插件开发起来好简单啊……

掩面而泣

二、 代码实现


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表