如何通过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
最满意答案
我试过,但这段代码完全正常:
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'
相关问答
更多-
ZF2更改我的表达式并返回错误(Postgre,Distinct)(ZF2 changing my expression and returning error (Postgre, Distinct))[2022-04-01]
试试下面的代码 $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 ...
-
ZF2改变扩展类(ZF2 change extends class)[2023-09-18]
我能想到的解决方案是重写自动加载器的一部分。 在自动加载函数中,添加额外的检查来检查请求的类是否为\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) ...
-
在ZF2中解析日期(Parse date in ZF2)[2022-09-26]
不知道什么样的数据库后端和关系映射,但问题与我想象的日期存储方式有关,很可能是: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_ ...
-
zf2 csrf无法正常工作(zf2 csrf not working)[2022-03-26]
据我所知,从代码中可以看出,为了保持向后兼容性,这是预期的行为。 字符串的第二部分是用于跟踪同一会话中的多个反CSRF令牌的令牌ID(不是实际的反CSRF令牌)。 如果在验证期间没有设置ID(如在您的示例中),则代码仅检查会话存储中的哈希。 源代码表明这是为了避免BC中断( 参见源代码 ) 如果您真的想要强制执行令牌ID,可以扩展Zend\Validator\Csrf并覆盖getValidationToken() (即删除BC代码): class MyCustomCsrf extends \Zend\Val ...