110,536
社区成员
发帖
与我相关
我的任务
分享
CancellationTokenSource canceltoken = new CancellationTokenSource();
var task = new Task(() =>
{
try
{
for (int i = 0; i < 1000; i++)
{
if (canceltoken.Token.IsCancellationRequested)
{
Console.WriteLine("CancellationRequested!");
throw new OperationCanceledException(canceltoken.Token);
}
else
{
Console.WriteLine("i={0}", i);
Thread.Sleep(1 * 1000);
throw new Exception("1222");
}
}
}
catch (TaskCanceledException TCEx)
{
Console.WriteLine("TCEx:" + TCEx.Message);
}
catch (Exception Ex)
{
Console.WriteLine("Ex:" + Ex.Message);
}
}, canceltoken.Token);
var task1 = task.ContinueWith((preTask) =>
{
try
{
if ((preTask.IsCanceled == false) && (preTask.IsCompleted == true) && (preTask.IsFaulted == false))
{
}
for (int i = 0; i < 1000; i++)
{
if (canceltoken.Token.IsCancellationRequested)
{
Console.WriteLine("CancellationRequested_1!");
throw new OperationCanceledException(canceltoken.Token);
}
else
{
Console.WriteLine("1 i={0}", i);
Thread.Sleep(1 * 1000);
}
}
}
catch (TaskCanceledException TCEx)
{
Console.WriteLine("TCEx:" + TCEx.Message);
}
catch (Exception Ex)
{
Console.WriteLine("Ex:" + Ex.Message);
}
}, canceltoken.Token);
task.Start();
var task1 = Task.Factory.StartNew(() =>
{
byte[] mBT = new byte[1];
mBT[0] = 0x00;
mBT[1] = 0x01;
//throw new Exception("I'm bad, but not too bad!");
});
try
{
task1.Wait();
}
catch (AggregateException ae)
{
foreach (var a in ae.InnerExceptions)
{
Console.WriteLine(task1.IsFaulted); //这里将输出True,表示task1任务失败了
Console.WriteLine(a.Message);
}
}
Console.WriteLine("press any key to continue");
Console.Read();
var task1 = Task.Factory.StartNew(() =>
{
throw new Exception("I'm bad, but not too bad!");
});
try
{
task1.Wait();
}
catch (AggregateException ae)
{
foreach (var a in ae.InnerExceptions)
{
Console.WriteLine(task1.IsFaulted); //这里将输出True,表示task1任务失败了
Console.WriteLine(a.Message);
}
}
Console.Read();
var task1 = Task.Factory.StartNew(() =>
{
for (int i = 0; i < 1000; i++)
{
MessageBox.Show(i.ToString());
Thread.Sleep(2000);
throw new Exception("I'm bad, but not too bad!");
}
}).ContinueWith((t) =>
{
MessageBox.Show("success");
}, TaskContinuationOptions.NotOnFaulted);
try
{
方法1();
方法2();
}
catch(Exception ex)
{
Console.WriteLine("{0}:{1}", ex.GetType().Name, ex.Message);
}