private static void AExceptionCatched(object sender, AggregateExceptionArgs e) { foreach (var item in e.AggregateException.InnerExceptions) { Util.Print("Exc type: {0}{1}from: {2}{3}content: {4}", item.GetType(), Util.NewLine, item.Source, Util.NewLine, item.Message); } }
public async Task ShowWhenDownloading() { this.Topmost = true; this.Show(); await Task.Factory.StartNew(() => { try { EventWaitHandle _waitHandle = new AutoResetEvent(false); App.downloader.DownloadCompleted += (a, b) => { this.Dispatcher.Invoke(new Action(() => { try { this.Close(); } catch (Exception) { } })); _waitHandle.Set(); }; _waitHandle.WaitOne(); } catch (Exception ex) { AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; App.CatchAggregateException(this, args); } }); }
public void Mainc( ) { AggregateExceptionCatched += //EventHandler<AggregateExceptionArgs> (Program_AggregateExceptionCatched); Task t = new Task(() => { try { throw new InvalidOperationException("任务并行编码中产生的未知异常"); } catch (Exception err) { AggregateExceptionArgs errArgs = new AggregateExceptionArgs() { AggregateException = new AggregateException(err) }; AggregateExceptionCatched(null, errArgs); } }); t.Start(); Console.WriteLine("主线程马上结束"); Console.ReadKey(); }
public static void ExByEvent() { AggregateExceptinCatched += Program_AggregateExceptionCatched; Task t = new Task(() => { try { throw new InvalidOperationException("sdddsddddEX"); } catch (Exception ex) { AggregateExceptionArgs exArgs = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex), }; AggregateExceptinCatched(null, exArgs); } }); t.Start(); Console.WriteLine("ExByEvent end"); }
//private static EventHandler<T> EventHandler<T>(Action<object, T> program_AggregateExceptionCatched) //{ // throw new NotImplementedException(); //} static void Program_AggregateExceptionCatched(object sender, AggregateExceptionArgs e) { foreach (var item in e.AggregateException.InnerExceptions) { Console.WriteLine("异常类型:{0}{1}来自:{2}{3}异常内容:{4}", item.GetType(), Environment.NewLine, item.Source, Environment.NewLine, item.Message); } }
private void Notifi_AggregateExceptCatched(object sender, AggregateExceptionArgs e) { foreach (var item in e.AggregateException.InnerExceptions) { Console.WriteLine("异常类型:{0},{1} 来自内容:{2},{3} 异常内容:{4}", item.GetType(), Environment.NewLine , item.Source, Environment.NewLine, item.Message); } }
void Program_AggregateExceptionCatched(object sender, AggregateExceptionArgs e) { foreach (var item in e.AggregateException.InnerExceptions) { LogUtil.HWLogger.UI.ErrorFormat("异常类型:{0}{1}来自:{2}{3}异常内容:{4}", item.GetType(), Environment.NewLine, item.Source, Environment.NewLine, item.Message); } }
/// <summary> /// 例外事件顯示 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void Program_AggregateExceptionChanged(object sender, AggregateExceptionArgs e) { foreach (var item in e.AggregateExceptio.InnerExceptions) { Console.WriteLine($@"異常類型: {item.GetType()}"); Console.WriteLine($@"來自: {item.Source}"); Console.WriteLine($@"異常內容: {item.Message}"); } }
static void Program_AggregateExceptionCatched(object sender, AggregateExceptionArgs e) { string errorMessage = null; foreach (var item in e.AggregateException.InnerExceptions) { errorMessage += $"{item.Message}\n"; } MessageBox.Show(errorMessage); }
void BatchExportCitForm_AggregateExceptionCatched(object sender, AggregateExceptionArgs e) { string ex = ""; foreach (var item in e.AggregateException.InnerExceptions) { ex += string.Format("异常类型:{0}{1}来自:{2}{3}异常内容:{4}", item.GetType(), Environment.NewLine, item.Source, Environment.NewLine, item.Message); } MessageBox.Show(ex); }
private void Home_Load(object sender, EventArgs e) { PleaseWait pleaseWait = new PleaseWait(pnlLoading, Properties.Resources.loading_01, "正在加载第一个任务..."); pleaseWait.Show(); AggregateExceptionCatched += new EventHandler <AggregateExceptionArgs>(Program_AggregateExceptionCatched); var backgroundScheduler = TaskScheduler.Default; var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; Task.Factory.StartNew(delegate { try { Thread.Sleep(2000); ThrowTestException(); cts.Cancel(); pleaseWait.Close(); } catch (Exception ex) { cts.Cancel(); pleaseWait.Close(); AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; // 使用主线程委托代理,处理子线程 异常 // 这种方式没有阻塞 主线程或其他线程 AggregateExceptionCatched?.Invoke(null, args); } }, token, TaskCreationOptions.None, backgroundScheduler) .ContinueWith(delegate { pleaseWait.Refresh("正在加载第二个任务"); }, token, TaskContinuationOptions.None, uiScheduler) .ContinueWith(delegate { Thread.Sleep(2000); }, token, TaskContinuationOptions.None, backgroundScheduler) .ContinueWith(delegate { pleaseWait.Refresh("正在加载第三个任务"); pleaseWait.Close(); }, token, TaskContinuationOptions.None, uiScheduler); //var complexTask = Task.WhenAll(task); //complexTask.ContinueWith() }
private async Task AppendVersionsDownloadTask(IList list) { await Task.Factory.StartNew(() => { try { foreach (JWVersion item in list) { string json = FunctionAPIHandler.HttpGet(apiHandler.DoURLReplace(item.Url)); Core.Modules.Version ver = App.handler.JsonToVersion(json); string jsonPath = App.handler.GetJsonPath(ver.ID); string dir = Path.GetDirectoryName(jsonPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.WriteAllText(jsonPath, json); List <DownloadTask> tasks = new List <DownloadTask>(); tasks.Add(new DownloadTask("资源引导", apiHandler.DoURLReplace(ver.AssetIndex.URL), App.handler.GetAssetsIndexPath(ver.Assets))); tasks.AddRange(Core.Util.GetLost.GetLostDependDownloadTask(App.config.MainConfig.Download.DownloadSource, App.handler, ver)); App.downloader.SetDownloadTasks(tasks); App.downloader.StartDownload(); } } catch (WebException ex) { this.Dispatcher.Invoke(new Action(() => { this.ShowMessageAsync("获取版本信息失败", "请检查您的网络是否正常或更改下载源/n原因:" + ex.Message); })); } catch (Exception ex) { AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; App.CatchAggregateException(this, args); } }); }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) { AggregateExceptionCatched += new EventHandler <AggregateExceptionArgs>(Program_AggregateExceptionCatched); return(Task.Factory.StartNew(() => { var buffer = new Byte[this.bufferSize]; long size; TryComputeLength(out size); var uploaded = 0; using (var sinput = content.ReadAsStreamAsync().Result) { while (true) { try { var length = sinput.Read(buffer, 0, buffer.Length); if (length <= 0) { break; } //downloader.Uploaded = uploaded += length; uploaded += length; progress?.Invoke(uploaded, size); //System.Diagnostics.Debug.WriteLine($"Bytes sent {uploaded} of {size}"); stream.Write(buffer, 0, length); stream.Flush(); } catch (Exception ex) { AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; //使用主线程委托代理,处理子线程 异常 //这种方式没有阻塞 主线程或其他线程 AggregateExceptionCatched?.Invoke(null, args); break; } } } stream.Flush(); })); }
private async Task AppendForgeDownloadTask(Version ver, JWForge forge) { try { //string json = await APIRequester.HttpGetStringAsync(apiHandler.DoURLReplace(item.Url)); //Version ver = App.handler.JsonToVersion(json); //string jsonPath = App.handler.GetJsonPath(ver.ID); //string dir = Path.GetDirectoryName(jsonPath); //if (!Directory.Exists(dir)) //{ // Directory.CreateDirectory(dir); //} //File.WriteAllText(jsonPath, json); //List<DownloadTask> tasks = new List<DownloadTask>(); //tasks.Add(new DownloadTask("资源引导", apiHandler.DoURLReplace(ver.AssetIndex.URL), App.handler.GetAssetsIndexPath(ver.Assets))); //tasks.AddRange(await NsisoLauncherCore.Util.FileHelper.GetLostDependDownloadTaskAsync(App.config.MainConfig.Download.DownloadSource, App.handler, ver)); //App.downloader.SetDownloadTasks(tasks); //App.downloader.StartDownload(); } catch (WebException ex) { this.Dispatcher.Invoke(new Action(() => { this.ShowMessageAsync("获取版本信息失败", "请检查您的网络是否正常或更改下载源/n原因:" + ex.Message); })); } catch (Exception ex) { AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; App.CatchAggregateException(this, args); } }
public void AppendLog(object sender, Log log) { OnLog?.Invoke(sender, log); if (WriteToFile) { Task.Factory.StartNew(() => { try { LogLock.EnterWriteLock(); try { if (log.LogLevel == LogLevel.GAME) { File.AppendAllText("log.txt", string.Format("[GAME]{0}\r\n", log.Message)); } else { File.AppendAllText("log.txt", string.Format("[{0}][{1}]{2}\r\n", DateTime.Now.ToString(), log.LogLevel, log.Message)); } } catch (Exception) { } finally { LogLock.ExitWriteLock(); } } catch (Exception ex) { AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; App.CatchAggregateException(this, args); } }); } }
public static void T2() { AggregateExceptionCatched += new EventHandler <AggregateExceptionArgs>(AExceptionCatched); Task t = new Task(() => { try { throw new InvalidOperationException("Unknown exception in cussss"); } catch (Exception err) { AggregateExceptionArgs arg = new AggregateExceptionArgs() { AggregateException = new AggregateException(err) }; AggregateExceptionCatched(null, arg); } }); t.Start(); Util.Print("Main Thread Exit right away..."); }
/// <summary> /// 使用通知的方式,不阻塞主线程捕获异常 /// </summary> public void Test04() { aggregateExceptCatched += Notifi_AggregateExceptCatched; Task t = new Task(() => { try { throw new Exception("任务并行编码中产生的位置异常"); } catch (Exception e) { AggregateExceptionArgs errArgs = new AggregateExceptionArgs() { AggregateException = new AggregateException(e) }; aggregateExceptCatched(this, errArgs); } }); t.Start(); Console.WriteLine("主线程马上结束"); Thread.Sleep(3000); }
public async Task <DownloadCompletedArg> ShowWhenDownloading() { this.Topmost = true; this.Show(); return(await Task.Run(() => { DownloadCompletedArg completedArg = null; try { EventWaitHandle _waitHandle = new AutoResetEvent(false); App.Downloader.DownloadCompleted += (a, b) => { this.Dispatcher.Invoke(new Action(() => { try { this.Close(); } catch (Exception) { } })); _waitHandle.Set(); completedArg = b; }; _waitHandle.WaitOne(); } catch (Exception ex) { AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; App.CatchAggregateException(this, args); } return completedArg; })); }
private void TaskBestThrowException() { Console.WriteLine("003.Task 發生例外的最佳範例-使用事件"); //註冊採集例外事件 AggregateExceptionCatched += new EventHandler <AggregateExceptionArgs>(Program_AggregateExceptionChanged); Task t = new Task(() => { try { throw new InvalidOperationException(" Task 拋出例外"); } catch (Exception err) { AggregateExceptionArgs errArgs = new AggregateExceptionArgs() { AggregateExceptio = new AggregateException(err) }; AggregateExceptionCatched(null, errArgs); } }); t.Start(); Console.WriteLine("事件通知 Exception 結束"); }
///上传签名 /// </summary> public CommonResponse UploadSignature(object eventData) { var ret = new CommonResponse("0"); var jsData = JsonUtil.SerializeObject(eventData); var request = JsonUtil.DeserializeObject <CommonRequest>(jsData); ret.Ips = request.Ips; if (!File.Exists(request.Data.ToString())) { ret.Code = ErrorCode.FILE_NOTFOUND; LogUtil.HWLogger.UI.Error("Upload Signatur failed: File path error,error path " + request.Data.ToString()); return(ret); } var fusionDirector = FusionDirectorWorker.Instance.FindByIP(request.Ips[0]); if (fusionDirector == null) { ret.Code = ErrorCode.NET_FD_NOFOUND; LogUtil.HWLogger.UI.Error("Upload Signatur failed: not found Fd" + request.Ips[0].ToString()); return(ret); } AggregateExceptionCatched2 += new EventHandler <AggregateExceptionArgs>(Program_AggregateExceptionCatched2); TokenSource2 = new CancellationTokenSource(); Task.Factory.StartNew(() => { try { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(fusionDirector.LoginAccount + ":" + fusionDirector.LoginPwd); var authStr = "Basic " + Convert.ToBase64String(bytes); var remoteUrl = "https://" + fusionDirector.HostIP + ":" + fusionDirector.Port + "/redfish/v1" + request.Endpoint; //默认忽略证书 ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; //兼容所有ssl协议 ServicePointManager.SecurityProtocol = (SecurityProtocolType)(3072 | 768 | 192 | 48); var file = File.Open(request.Data.ToString(), FileMode.Open, FileAccess.Read); ret.Description = Math.Round((decimal)file.Length / (1024 * 1024), 0).ToString(); var fileContent = new StreamContent(file) { Headers = { ContentLength = file.Length, ContentType = new MediaTypeHeaderValue("application/octet-stream") } }; var formDataContent = new MultipartFormDataContent(); var fileName = file.Name.Substring(file.Name.LastIndexOf('\\') + 1); formDataContent.Add(fileContent, "tiFile", fileName); var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, remoteUrl); var progressContent = new ProgressableStreamContent(formDataContent, 4096 * 100, (sent, total) => { try { var Progress = Convert.ToInt32(Math.Round((decimal)sent / total, 2) * 100); FDBrowser.ExecuteScriptAsync("setUploadSignaturProgress", Progress);//设置升级包上传进度 setUploadSignaturProgress是UI js方法名称 Progress是进度 0-100 } catch (Exception ex) { AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; //使用主线程委托代理,处理子线程 异常 //这种方式没有阻塞 主线程或其他线程 AggregateExceptionCatched1?.Invoke(null, args); throw ex; } }); httpRequestMessage.Content = progressContent; httpRequestMessage.Headers.Add("Authorization", authStr); using (HttpClient httpClient = new HttpClient()) { var httpResponse = httpClient.SendAsync(httpRequestMessage, TokenSource2.Token).Result; var statusCode = ((int)httpResponse.StatusCode).ToString(); var resultStr = httpResponse.Content.ReadAsStringAsync().Result; LogUtil.HWLogger.API.Info("URL:" + remoteUrl + " Api Result:" + resultStr); ret.Data.Add(new Item() { Ip = fusionDirector.HostIP, Code = statusCode, Data = JsonConvert.DeserializeObject(resultStr) }); if (!statusCode.StartsWith("2")) { throw new BaseException(statusCode, ""); } fileContent.Dispose(); } file.Dispose(); } catch (BaseException ex) { LogUtil.HWLogger.UI.Error("Upload Signatur failed: ", ex); ret.Code = ex.Code; } catch (Exception ex) { LogUtil.HWLogger.UI.Error("Upload Signatur failed: ", ex); ret.Code = ErrorCode.SYS_UNKNOWN_ERR; AggregateExceptionArgs args = new AggregateExceptionArgs() { AggregateException = new AggregateException(ex) }; //使用主线程委托代理,处理子线程 异常 //这种方式没有阻塞 主线程或其他线程 AggregateExceptionCatched2?.Invoke(null, args); } ret.Ips = request.Ips; FDBrowser.ExecuteScriptAsync("uploadSignaturFileSuccess", JsonConvert.SerializeObject(ret));//执行升级包上传成功方法 uploadSignaturFileSuccess是UI js升级包上传成功方法 }); return(ret); }