首页 / C# / c# – 在哪里处理Task抛出的异常
c# – 在哪里处理Task抛出的异常
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 在哪里处理Task抛出的异常,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2248字,纯文字阅读大概需要4分钟。
内容图文
我在单独的任务中执行一些轮询IO循环.这些循环可能会遇到异常.如果遇到异常,我想提醒调用者,以便它可以:
>记录下来
>杀死所有IO线程
>重置连接
>重启IO线程
用户界面必须保持响应.处理此方案的首选方法是什么?我在下面列出了一个说明性的程序.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TaskExceptionCatching
{
class Program
{
static void Main(string[] args)
{
startLoops();
System.Console.WriteLine("Type 'Exit' when you're ready to stop.");
while (System.Console.ReadLine() != "Exit")
{
System.Console.WriteLine("Seriously, just type 'Exit' when you're ready to stop.");
}
}
static private void startLoops()
{
System.Console.WriteLine("Starting fizzLoop.");
var fizzTask = Task.Factory.StartNew(new Action(fizzLoop));
System.Console.WriteLine("Starting buzzLoop.");
var buzzTask = Task.Factory.StartNew(new Action(buzzLoop));
}
static private void fizzLoop()
{
while (true)
{
//simulate something error prone, like some risky IO
System.Threading.Thread.Sleep(200);
bool isErr = (new Random().Next(1, 100) == 10);
if (isErr)
throw new Exception("Fizz got an exception.");
}
}
static private void buzzLoop()
{
while (true)
{
//simulate something error prone, like some risky IO
System.Threading.Thread.Sleep(200);
bool isErr = (new Random().Next(1, 100) == 10);
if (isErr)
throw new Exception("Buzz got an exception.");
}
}
}
}
解决方法:
这可能是异常void方法可能很方便的极少数情况之一:
static async void StartAndMonitorAsync(Func<Task> taskFunc)
{
while (true)
{
var task = taskFunc();
try
{
await task;
// process the result if needed
return;
}
catch (Exception ex)
{
// log the error
System.Console.WriteLine("Error: {0}, restarting...", ex.Message);
}
// do other stuff before restarting (if any)
}
}
static private void startLoops()
{
System.Console.WriteLine("Starting fizzLoop.");
StartAndMonitorAsync(() => Task.Factory.StartNew(new Action(fizzLoop)));
System.Console.WriteLine("Starting buzzLoop.");
StartAndMonitorAsync(() => Task.Factory.StartNew(new Action(buzzLoop)));
}
如果你不能使用async / await,可以使用Task.ContinueWith实现类似的逻辑.
如果可以多次调用startLoops(当任务已经“在飞行中”时),则需要使用CancelltionToken(“A pattern for self-cancelling and restarting task”中的更多详细信息)向StartAndMonitorAsync及其启动的任务添加取消逻辑.
内容总结
以上是互联网集市为您收集整理的c# – 在哪里处理Task抛出的异常全部内容,希望文章能够帮你解决c# – 在哪里处理Task抛出的异常所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。