我在 Winform 中创建了一个测试应用程序来学习任务(c#)中的异常处理。目标框架是4.0。以下是我的异常处理代码
var task = Task.Factory.StartNew<DataTable>(() => getDataTable(Convert.ToInt32 (this.textBoxOptionVal.Text)));
task.ContinueWith(t =>
{
this.dataGridViewData.DataSource = t.Result as DataTable;
this.textBoxRetVal.Text = "Success" ;
},
CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
task.ContinueWith(t =>
{
// Update UI (and UI-related data) here: failed status.
// t.Exception contains the occured exception.
AggregateException aggregateException = t.Exception;
aggregateException.Handle(exception => true);
this.dataGridViewData.DataSource = null;
this.textBoxRetVal.Text = "Exception Thrown";
},
CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.FromCurrentSynchronizationContext());
Run Code Online (Sandbox Code Playgroud)
这很好用。getDataTable如果方法抛出任何异常,则continuewith OnlyOnFaulted执行该代码块。但后来我注释掉了块中的所有语句ContinueWith OnlyOnfaulted,并添加了一个config包含以下内容的文件
<?xml version="1.0"?>
<configuration>
<runtime>
<ThrowUnobservedTaskExceptions enabled="true"/>
</runtime> …Run Code Online (Sandbox Code Playgroud) 我正在尝试修复 C# 异步代码,启动在非托管 C++ 例程编写的外部 dll 中执行的可取消操作。
如果用户委托调用外部非托管 C++ 例程,是否有办法使用在创建时传递给任务的取消令牌来取消任务?
据我所知,任务取消涉及用户委托和请求取消的代码之间的合作。成功的取消涉及请求代码调用 CancellationTokenSource.Cancel 方法,以及用户委托及时终止操作,方法是在注意到已提出取消请求时简单地从委托返回(通过轮询 CancellationToken.IsCancellationRequested)方法)或使用 CancellationToken.ThrowIfCancellationRequested 方法抛出 OperationCanceledException。(参见http://msdn.microsoft.com/en-us/library/dd997396%28v=vs.110%29.aspx)
这两种方式涉及由用户委托执行的非托管 C++ 例程通过接收 CancellationToken 作为参数并定期调用其 IsCancellationRequested 和/或 ThrowIfCancellationRequested 方法来进行协作。
是否可以从非托管外部 C++ 例程执行此操作?
如果不是,当请求代码请求取消时,是否有办法强制终止执行用户委托的任务(执行非托管 C++ 例程)?
以下是我尝试修复的混合 C# / C++Cli / 非托管 C++ 代码的示例(摘录),以便能够取消用户委托在 C++ 非托管代码部分中执行的操作:
FrmDemo.cs:-------------------------------------------------------- ----------------------------
public class FrmDemo : Form
{
private CliClass m_CliObject;
private System.Threading.CancellationTokenSource m_Cts;
private System.Threading.CancellationToken m_Ct;
private void FrmDemo_Load(object sender, EventArgs e)
{
// Creating the external CliObject:
this.m_CliObject = new NSDemo.CliClass();
...
}
// …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个 Windows 服务,该服务每 5 分钟轮询一次系统并检查是否需要执行某些操作。我已经阅读了WaitHandles它们在该领域的有用性,但需要了解它是如何工作的。
参见下面的代码:
public partial class PollingService : ServiceBase
{
private CancellationTokenSource cancelToken = new CancellationTokenSource();
private Task mainTask = null;
public PollingService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
mainTask = new Task(pollInterval, cancelToken.Token, TaskCreationOptions.LongRunning);
mainTask.Start();
}
public void pollInterval()
{
CancellationToken cancel = cancelToken.Token;
TimeSpan interval = TimeSpan.FromMinutes(5);
while (!cancel.IsCancellationRequested && !cancel.WaitHandle.WaitOne(interval))
{
if (cancel.IsCancellationRequested)
{
break;
}
EventLog.WriteEntry("*-HEY MAN I'M POLLNG HERE!!-*");
//Polling code goes here. Checks periodically IsCancellationRequested
} …Run Code Online (Sandbox Code Playgroud) 我查看了其他问题中有关任务计划程序的所有 PowerShell 脚本的答案,但无法找到可以解决此问题的脚本。
我尝试使用以下命令直接通过任务计划程序运行 PowerShell 脚本:
powershell.exe -file c:\path_to_your_script\script.ps1
Run Code Online (Sandbox Code Playgroud)
以及创建一个批处理来运行 PowerShell 脚本。
PowerShell 脚本在单独运行以及手动批处理运行时都能完美运行。
它打开一个 Excel,刷新它,保存,然后关闭。
我无法通过任务处理程序成功安排此操作。
有什么建议吗?
感谢您的帮助
编辑:
@luke这是任务计划程序设置的导出
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2015-05-11T12:40:51.6084684</Date>
<Author>----------</Author>
</RegistrationInfo>
<Triggers>
<TimeTrigger>
<Repetition>
<Interval>PT1H</Interval>
<StopAtDurationEnd>false</StopAtDurationEnd>
</Repetition>
<StartBoundary>2015-05-11T12:30:00</StartBoundary>
<Enabled>true</Enabled>
</TimeTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>------\Administrator</UserId>
<LogonType>Password</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>true</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>true</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>true</WakeToRun>
<ExecutionTimeLimit>P3D</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>C:\Windows\System32\cmd.exe</Command>
<Arguments>/q /c "C:\Users\---------\Documents\PowerBI\PowerShell\RunExcelRefreshingScriptPowerShell2.bat"</Arguments>
</Exec>
</Actions>
</Task>
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
var result = MessageBoxHelper.MsgBox
.ShowAsync("Press Yes to proceed", MessageBoxButton.YesNo)
.ContinueWith((answer) =>
{
if (answer.Result == MessageBoxResult.Yes)
{
Task<bool> asyncTask = ExecuteAsyncFunc();
//asyncTask.Unwrap(); ??
asyncTask.ContinueWith((a) =>
{
// More
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
}, TaskContinuationOptions.OnlyOnRanToCompletion);
}
Run Code Online (Sandbox Code Playgroud)
在其他地方调用是这样的:
public async Task<bool> ExecuteAsyncFunc()
{
await CallAnotherAsyncFunction();
}
Run Code Online (Sandbox Code Playgroud)
我相信我需要调用 Unwrap(),我已经尝试过,因为我在块内调用 wait ContinueWith()。但是,当我取消注释时,出现以下错误:
错误 CS1929“任务”不包含“展开”的定义,并且最佳扩展方法重载“TaskExtensions.Unwrap(Task)”需要“任务”类型的接收器
我是否需要在这种情况下使用 Unwrap?如果需要,我做错了什么?
我有一个看起来很简单的问题,但我似乎无法在任何地方找到答案。
鉴于我有多个不同类型的任务数组,例如
Task<Dog>[] dogTasks = GetDogTasks();
Task<Cat>[] catTasks = GetCatTasks();
Task<Fish>[] fishTasks = GetFishTasks();
Run Code Online (Sandbox Code Playgroud)
完成这些任务的最佳方法是什么WaitAll()?
我在使用以下示例时遇到问题:
public void Method()
{
LongRunningMethod();
}
Run Code Online (Sandbox Code Playgroud)
LongRunningMethod()调用大约需要 5 秒。我是Method()从 UI 线程调用的,所以它显然应该冻结 UI。解决方案是Method()在新的环境中运行Task,所以我像这样运行它:
Task.Factory.StartNew(()=>{Method()})
Run Code Online (Sandbox Code Playgroud)
它仍然阻塞 UI,所以我想是否LongRunningMethod()可能使用 UI 上下文。然后我尝试了另一种解决方案:
new Thread(()=>Method()).Start()
它开始起作用了。这怎么可能?我知道这Task不能保证在不同的线程上运行,但CLR应该足够聪明来找出它是长时间运行的方法。
在 Visual Studio Code 中,我在 tsconfig.json 的代码中有以下代码
{
"version": "1.6.0",
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true,
"watch": true,
"experimentalAsyncFunctions": true,
"isolatedModules": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"preserveConstEnums": true,
"suppressImplicitAnyIndexErrors": true
},
...
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,该watch选项为 true。好吧,看起来这不足以将 .ts 文件编译为 .js,就像atom-typescript 那样。基本上,保存 .ts 时,新编译的 .js 应该与 .ts 文件位于同一目录中。
另外,我想避免在我的根项目中使用 gulp,因为我已经将 gulpfile.coffee 用于其他方式。有人有线索吗?
我使用过很多分发任务包,例如celery,,python-rq它们都依赖于外部服务,例如redis,rabbit-mq等等。
但是,通常我不需要queue service,换句话说,不想redis在我的vps上安装或其他非python服务。(也是为了简化环境)
producer我应该说,拆分和worker不同的进程(两个代码文件)是很好的。使用multiprocessing.Queue需要将所有内容放入一个文件中,并且需要编写大量附加代码来捕获ctrl+c以处理exit并保存当前排队的任务。celery使用,不会发生这种情况python-rq,尽管停止工作人员和生产者,但任务仍然保存在队列中。
我想使用本地队列(可以通过pip install xxx),例如磁盘队列。经过一番搜索,只找到了queuelib(持久(基于磁盘)队列的集合),但遗憾的是它不支持多进程访问。
我正在尝试向我的任务添加一个与 -task 完全相同的gen任务:gen2build.gradleJar
version = "0.0.1"
apply plugin: 'java'
task('gen', type: Jar) {
}
task gen2(type: Jar)
Run Code Online (Sandbox Code Playgroud)
跑步
gradle jar
Run Code Online (Sandbox Code Playgroud)
.class运行时生成包含文件的 JAR 文件
gradle gen
Run Code Online (Sandbox Code Playgroud)
或者
gradle gen2
Run Code Online (Sandbox Code Playgroud)
生成不包含任何文件的JAR 文件.class。
我的类定义有什么问题吗?
task ×10
c# ×6
asynchronous ×3
.net-4.0 ×1
async-await ×1
build.gradle ×1
c++-cli ×1
cancellation ×1
exception ×1
gradle ×1
interop ×1
jar ×1
powershell ×1
python ×1
queue ×1
tsc ×1
tsd ×1
typescript ×1
waithandle ×1
wpf ×1