我尝试将try catch放在Task.WhenAll(任务)周围,但它没有抓到任何东西。在我的一个任务中,我试图通过在空字符串上使用Substring来人为地生成异常。但所有发生的事情都是应用程序崩溃,默认为Application_UnhandledException。
private async void RunTasks()
{
tasks[0] = HttpExtensions.GetMyData("http://www....");
tasks[1] = HttpExtensions.GetMyData("http://www.....");
tasks[2] = GeoLocate.OneShotGeoLocate();
try
{
await Task.WhenAll(tasks);
}
catch (AggregateException ae)
{
App.ViewModel.ErrorMessage = ae.Message;
}
}
答案 0 :(得分:1)
要从执行任务中获取所有异常,请使用以下命令:
public static class Resize
{
public static void ResizeImage(string fileName)
{
ResizeImage(fileName, 1000, 1000, true);
}
public static void ResizeImage(string fileName, int newHeight, int newWidth, bool keepAspectRatio = true)
{
string saveto = Path.GetDirectoryName(fileName) + @"\Alternate\" + Path.GetFileName(fileName);
try
{
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
using (Image ImageFromStream = Image.FromStream(fs))
{
var ImageSize = new Size(newHeight, newWidth);
if (keepAspectRatio)
{
int oWidth = ImageFromStream.Width;
int oHeight = ImageFromStream.Height;
double pWidth = ((double)ImageSize.Width / (double)oWidth);
double pHeight = ((double)ImageSize.Height / (double)oWidth);
double percent;
if (pHeight < pWidth)
percent = pHeight;
else
percent = pWidth;
newWidth = (int)(oWidth * percent);
newHeight = (int)(oHeight * percent);
}
else
{
newWidth = ImageSize.Width;
newHeight = ImageSize.Height;
}
var ResizedImage = new Bitmap(newWidth, newHeight);
using (Graphics gfxHandle = Graphics.FromImage(ResizedImage))
{
gfxHandle.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfxHandle.DrawImage(ImageFromStream, 0, 0, newWidth, newHeight);
if (!Directory.Exists(Path.GetDirectoryName(saveto))) { Directory.CreateDirectory(Path.GetDirectoryName(saveto)); }
ResizedImage.Save(saveto, ImageFormat.Jpeg);
}
ResizedImage.Dispose();
ResizedImage = null;
}
}
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("Exception: {0}", ex.Message));
}
}
答案 1 :(得分:0)
这要归功于'nakiya'
private async void RunTasks()
{
tasks[0] = HttpExtensions.GetMyData("http://www....");
tasks[1] = HttpExtensions.GetMyData("http://www.....");
tasks[2] = GeoLocate.OneShotGeoLocate();
try
{
await Task.WhenAll(tasks);
}
catch (Exception ae)
{
App.ViewModel.ErrorMessage = ae.Message;
}
}