取消背景工 [英] Cancelling background-worker

查看:93
本文介绍了取消背景工的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题,希望有人能够帮助我.

I have the following problem and I hope someone will be able to help me with it.

我在VB .net(2010)中有一个工人,该工人在运行Shell程序.

I have a worker in VB .net (2010) which runs a shell-program.

shell程序是一种服务,其输出类似于:

The shell program is a service and output stuff like:

Server initializing...
Server opening port...
more info...

我能够捕获" shell的输出并将其添加到文本框(使用设置文本功能).

I am able to 'catch' the output of the shell and add it to a textbox (using set text function).

并且我可以通过单击停止按钮来取消工作程序,但是当外壳没有更多输出时,我将无法再停止工作程序.

And I am able to Cancel the worker by clicking on a stopbutton, however when there is no more output by the shell I cannot stop the worker anymore.

至少我怀疑是这种情况.

At least i suspect that's the case.

我已经尝试检查endofstream(注释部分),但这不起作用.

I've tried checking for endofstream (commented section) but that doesn't work.

我还尝试用一些测试文本代替相同的代码来代替"clsProcess.StandardOutput.ReadLine",这也有效.

I've also tried to same code with some test text in stead of 'clsProcess.StandardOutput.ReadLine' and that also works.

所以我得出的结论是,它必须与clsProcess.StandardOutput.ReadLine位于末尾有关.

So I came to the conclusion it must have something to do with clsProcess.StandardOutput.ReadLine being at the end???

    Try
        clsProcess.StartInfo.UseShellExecute = False
        clsProcess.StartInfo.RedirectStandardOutput = True
        clsProcess.StartInfo.RedirectStandardError = True
        clsProcess.StartInfo.FileName = serverpath + config_executable
        clsProcess.StartInfo.CreateNoWindow = True
        clsProcess.Start()
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "Error starting server")
        Debug.Print(ex.Message)
    End Try

    Do While Not workerServer.CancellationPending
        Try
            'If Not clsProcess.StandardOutput.EndOfStream Then
            SetText(clsProcess.StandardOutput.ReadLine + vbNewLine)
            'End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error adding line to log")
        End Try

        Threading.Thread.Sleep(100)
    Loop

    clsProcess.Kill()

有什么想法吗?

提前谢谢!

此致

PH

推荐答案

大概是在另一个线程上发生的.尝试从GUI线程Kill()处理该过程,而不仅仅是设置CancellationPending.您正确地认为ReadLine()调用正在阻塞,一旦没有更多输出,就会导致while循环永远不会重新评估其条件.

Presumably this is happening on another thread. Try Kill()ing the process from the GUI thread instead of just setting CancellationPending. You are correct that the ReadLine() call is blocking, causing the while loop to never re-evaluate its condition once there is no more output.

从另一个线程杀死该进程应该起作用. (它可能会引发ReadLine()的异常,因此请为此做好准备.)

Killing the process from another thread should work. (It may throw an exception from ReadLine(), so be prepared for that.)

这篇关于取消背景工的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆