【发布时间】:2014-05-15 19:40:55
【问题描述】:
我正在单独的任务中执行一些轮询 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.");
}
}
}
}
【问题讨论】:
标签: c# .net multithreading task-parallel-library task