Task <CompilationResult> CompileAsync() { Debug.Assert(compileCodeState == null); if (compileCodeState != null) { throw new InvalidOperationException(); } var state = new CompileCodeState(); compileCodeState = state; return(Task.Run(() => { state.CancellationToken.ThrowIfCancellationRequested(); return languageCompiler.CompileAsync(state.CancellationToken); }, state.CancellationToken)); }
async Task StartCompileAsync() { Result = null; SetDiagnostics(Array.Empty <CompilerDiagnostic>()); bool canceled = false; Exception caughtException = null; CompilationResult?result = null; try { result = await CompileAsync(); } catch (OperationCanceledException) { canceled = true; } catch (Exception ex) { caughtException = ex; } ModuleImporter moduleImporterResult = null; var compilerDiagnostics = result?.Diagnostics ?? Array.Empty <CompilerDiagnostic>(); if (canceled) { // It gets canceled when the dialog box gets closed, or when Roslyn cancels the task // for some unknown reason. compilerDiagnostics = new CompilerDiagnostic[] { new CompilerDiagnostic(CompilerDiagnosticSeverity.Error, "The task was canceled", "DSWTF!", null, null), }; } else if (caughtException != null) { compilerDiagnostics = new CompilerDiagnostic[] { ToCompilerDiagnostic(caughtException) }; } else if (result?.Success == true) { try { moduleImporterResult = new ModuleImporter(methodToEdit.Module); moduleImporterResult.Import(result.Value.RawFile, result.Value.DebugFile, methodToEdit); compilerDiagnostics = moduleImporterResult.Diagnostics; if (compilerDiagnostics.Any(a => a.Severity == CompilerDiagnosticSeverity.Error)) { moduleImporterResult = null; } } catch (ModuleImporterAbortedException) { compilerDiagnostics = moduleImporterResult.Diagnostics; Debug.Assert(compilerDiagnostics.Length != 0); moduleImporterResult = null; } catch (Exception ex) { compilerDiagnostics = new CompilerDiagnostic[] { ToCompilerDiagnostic(ex) }; moduleImporterResult = null; } } SetDiagnostics(compilerDiagnostics); compileCodeState?.Dispose(); compileCodeState = null; CanCompile = true; if (moduleImporterResult != null) { Result = moduleImporterResult; CodeCompiled?.Invoke(this, EventArgs.Empty); } // The compile button sometimes doesn't get enabled again CommandManager.InvalidateRequerySuggested(); }