首页 \ 问答 \ 如何通过CancellationToken停止异步处理?(How can I stop async Process by CancellationToken?)

如何通过CancellationToken停止异步处理?(How can I stop async Process by CancellationToken?)

我发现在代码下执行某些进程而没有冻结UI。 按下“开始工作”按钮时执行此代码。 我认为用户可以通过“停止”按钮停止这项工作。 所以我在MSDN上发现了这篇文章.. https://msdn.microsoft.com/en-us/library/jj155759.aspx 。 但是,在此代码中应用此CancellationToken很难..任何人都可以帮助解决这个问题吗?

我只使用public static async Task<int> RunProcessAsync(string fileName, string args)方法。

代码(来自https://stackoverflow.com/a/31492250 ):

public static async Task<int> RunProcessAsync(string fileName, string args)
{
    using (var process = new Process
    {
        StartInfo =
        {
            FileName = fileName, Arguments = args,
            UseShellExecute = false, CreateNoWindow = true,
            RedirectStandardOutput = true, RedirectStandardError = true
        },
        EnableRaisingEvents = true
    })
    {
        return await RunProcessAsync(process).ConfigureAwait(false);
    }
}

// This method is used only for internal function call.
private static Task<int> RunProcessAsync(Process process)
{
    var tcs = new TaskCompletionSource<int>();

    process.Exited += (s, ea) => tcs.SetResult(process.ExitCode);
    process.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
    process.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);

    bool started = process.Start();
    if (!started)
    {
        //you may allow for the process to be re-used (started = false) 
        //but I'm not sure about the guarantees of the Exited event in such a case
        throw new InvalidOperationException("Could not start process: " + process);
    }

    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    return tcs.Task;
}

用法:

var cancelToken = new CancellationTokenSource();
int returnCode = async RunProcessAsync("python.exe", "foo.py", cancelToken.Token);
if (cancelToken.IsCancellationRequested) { /* something */ }

单击开始按钮时,它会启动一些python脚本。 当脚本运行并且用户想要停止它时,用户按下停止按钮。 然后程序在代码下执行。

cancelToken.Cancel();

非常感谢你阅读这个问题。


I found beneath code for execute some process without freezing UI. This code is executed when 'Start Work' button is pressed. And I think users would stop this work by 'Stop' button. So I found this article at MSDN.. https://msdn.microsoft.com/en-us/library/jj155759.aspx . But, It was hard that applying this CancellationToken at this code.. Anyone can help this problem?

I use public static async Task<int> RunProcessAsync(string fileName, string args) method only.

Code (From https://stackoverflow.com/a/31492250):

public static async Task<int> RunProcessAsync(string fileName, string args)
{
    using (var process = new Process
    {
        StartInfo =
        {
            FileName = fileName, Arguments = args,
            UseShellExecute = false, CreateNoWindow = true,
            RedirectStandardOutput = true, RedirectStandardError = true
        },
        EnableRaisingEvents = true
    })
    {
        return await RunProcessAsync(process).ConfigureAwait(false);
    }
}

// This method is used only for internal function call.
private static Task<int> RunProcessAsync(Process process)
{
    var tcs = new TaskCompletionSource<int>();

    process.Exited += (s, ea) => tcs.SetResult(process.ExitCode);
    process.OutputDataReceived += (s, ea) => Console.WriteLine(ea.Data);
    process.ErrorDataReceived += (s, ea) => Console.WriteLine("ERR: " + ea.Data);

    bool started = process.Start();
    if (!started)
    {
        //you may allow for the process to be re-used (started = false) 
        //but I'm not sure about the guarantees of the Exited event in such a case
        throw new InvalidOperationException("Could not start process: " + process);
    }

    process.BeginOutputReadLine();
    process.BeginErrorReadLine();

    return tcs.Task;
}

Usage :

var cancelToken = new CancellationTokenSource();
int returnCode = async RunProcessAsync("python.exe", "foo.py", cancelToken.Token);
if (cancelToken.IsCancellationRequested) { /* something */ }

When the start button clicked, it starts some python script. When script is running and user wants to stop it, user presses stop button. Then program executes below code.

cancelToken.Cancel();

Thank you very much for reading this question.


原文:https://stackoverflow.com/questions/34199628
更新时间:2024-04-29 12:04

最满意答案

我试过,但这段代码完全正常:

use Zend\Validator\Callback;

.....

array(
    'name' => 'Callback',
    'options' => array(
        'messages' => array(
            Callback::INVALID_VALUE => 'My custom message',
            Callback::INVALID_CALLBACK => 'My custom message'
        ),
        'callback' => function(){
                return false;
            }
    )
)

消息的关键是: callbackValue但我收到的消息是'My custom message'


I tried but this code works totally fine:

use Zend\Validator\Callback;

.....

array(
    'name' => 'Callback',
    'options' => array(
        'messages' => array(
            Callback::INVALID_VALUE => 'My custom message',
            Callback::INVALID_CALLBACK => 'My custom message'
        ),
        'callback' => function(){
                return false;
            }
    )
)

The key of the message is: callbackValue but the message I get is 'My custom message'

相关问答

更多
  • 试试下面的代码 $emprestimos = (new EmprestimoTable())->select(function(Select $select) use($cliente) { $select->columns([new Expression('DISTINCT(idcontrato) AS idcontrato'), '*']); $select->where->equalTo('numerobeneficio', $cliente->getBeneficio ...
  • 您正在通过ServiceManager创建表单。 $customForm = $realServiceLocator->get('My\Form\CustomForm'); 这意味着您在服务管理器而不是表单元素管理器中注册了抽象工厂。 通过这样做,将创建表单,而无需正确准备工厂的输入过滤器 。 将此配置移动到“form_elements”键。 'form_elements' => [ 'abstract_factories' => [ 'My\Form\FormAbstrac ...
  • 我能想到的解决方案是重写自动加载器的一部分。 在自动加载函数中,添加额外的检查来检查请求的类是否为\Zend\Form\View\Helper\FormInput ,并且如果是这种情况,则加载您的自定义FormInput。 在你自己的FormInput中,你不会扩展Zend FormInput,但是你创建它的一个副本,并修改需要修改的部分。 除非ZF2为其形式助手使用依赖注入,否则这是我能想到的唯一方法(不改变基本库代码)。 I am using composer to install ZF2. As co ...
  • 问题在于composer.json中的autoload指令,您不需要命名空间名称上的尾部斜杠。 此外,请确保您的类正确命名空间,并在顶部使用namespace Tealbury\Validator 。 The problem is with the autoload directive in composer.json, you don't need the trailing slash on the namespace name. Also, make sure your class is properl ...
  • 我试过,但这段代码完全正常: use Zend\Validator\Callback; ..... array( 'name' => 'Callback', 'options' => array( 'messages' => array( Callback::INVALID_VALUE => 'My custom message', Callback::INVALID_CALLBACK => 'My custom messa ...
  • 最简单的方法是修改视图助手;) 在你的module.config.php里面 'view_helpers' => [ 'factories' => [ 'formelementerrors' => function($vhm) { $fee = new \Zend\Form\View\Helper\FormElementErrors(); $fee->setAttributes([ 'class' => ...
  • 只需添加.po或.mo文件而不是.php ,例如: $translator = new Zend\I18n\Translator\Translator(); $translator->addTranslationFile( 'gettext' 'resources/languages/fr.mo', 'default', 'fr_FR' ); Zend\Validator\AbstractValidator::setDefaultTranslator($translator) ...
  • 不知道什么样的数据库后端和关系映射,但问题与我想象的日期存储方式有关,很可能是:Y / m / d 如果您保存并收到此错误,那就是因为您需要此格式的日期。 如果你正在保湿,你可能还需要一个日期策略来处理水合作用,如: // InputFilter.php class yourInputFilter() { $hydrator->getHydrator()->addStrategy('my_attribute', new MyDateHydrationStrategy()); $this ...
  • 解决方案是在测试中添加此行,foreach模型: $ bla = $ this-> getApplication() - > getServiceManager() - > get('Tests'); 谢谢你i336_ :) the solution is to add this line in the test, foreach model: $bla = $this->getApplication()->getServiceManager()->get('Tests'); Thank you i336_ ...
  • 据我所知,从代码中可以看出,为了保持向后兼容性,这是预期的行为。 字符串的第二部分是用于跟踪同一会话中的多个反CSRF令牌的令牌ID(不是实际的反CSRF令牌)。 如果在验证期间没有设置ID(如在您的示例中),则代码仅检查会话存储中的哈希。 源代码表明这是为了避免BC中断( 参见源代码 ) 如果您真的想要强制执行令牌ID,可以扩展Zend\Validator\Csrf并覆盖getValidationToken() (即删除BC代码): class MyCustomCsrf extends \Zend\Val ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。