Beispiel #1
0
        protected override void LoadComponentsInUIContext()
        {
            // we need to load it as early as possible since we can have errors from
            // package from each language very early
            this.ComponentModel.GetService <VisualStudioDiagnosticListTable>();
            this.ComponentModel.GetService <VisualStudioTodoListTable>();
            this.ComponentModel.GetService <VisualStudioDiagnosticListTableCommandHandler>().Initialize(this);

            this.ComponentModel.GetExtensions <IDefinitionsAndReferencesPresenter>();
            this.ComponentModel.GetExtensions <INavigableItemsPresenter>();
            this.ComponentModel.GetService <VisualStudioMetadataAsSourceFileSupportService>();
            this.ComponentModel.GetService <VirtualMemoryNotificationListener>();

            // The misc files workspace needs to be loaded on the UI thread.  This way it will have
            // the appropriate task scheduler to report events on.
            this.ComponentModel.GetService <MiscellaneousFilesWorkspace>();

            LoadAnalyzerNodeComponents();

            Task.Run(() => LoadComponentsBackgroundAsync());
        }
        /// <summary>注册区域,每个继承此区域特性的类的静态构造函数都调用此方法,以进行相关注册</summary>
        public static void RegisterArea <T>() where T : AreaBase
        {
            var areaType = typeof(T);
            var ns       = areaType.Namespace + ".Controllers";
            var areaName = areaType.Name.TrimEnd("Area");

            XTrace.WriteLine("开始注册权限管理区域[{0}],控制器命名空间[{1}]", areaName, ns);

            // 自动检查并添加菜单
            TaskEx.Run(() =>
            {
                try
                {
                    ScanController <T>();
                }
                catch (Exception ex)
                {
                    XTrace.WriteException(ex);
                }
            });
        }
Beispiel #3
0
        internal static Task LoadContentAsync(BlockingCollection <string> fName, BlockingCollection <string> lines)
        {
            return(Task.Run(async() =>
            {
                foreach (var f in fName.GetConsumingEnumerable())
                {
                    using (FileStream stream = File.OpenRead(f))
                    {
                        var reader = new StreamReader(stream);
                        string line = null;
                        while ((line = await reader.ReadLineAsync()) != null)
                        {
                            lines.Add(line);
                            ConsHelper.WriteLine($"Stage 2: Added {line}");
                        }
                    }
                }

                lines.CompleteAdding();
            }));
        }
Beispiel #4
0
        private void HandleActivity(string currentFile, bool isWrite)
        {
            if (currentFile == null)
            {
                return;
            }

            if (!isWrite && _lastFile != null && !EnoughTimePassed() && currentFile.Equals(_lastFile))
            {
                return;
            }

            Task.Run(() =>
            {
                SendHeartbeat(currentFile, isWrite);
            });


            _lastFile      = currentFile;
            _lastHeartbeat = DateTime.UtcNow;
        }
Beispiel #5
0
        public async Task GivenADeleteResourceRequest_WhenDeletingAnAlreadyDeletedSearchParameterResource_TheDeleteSearchParameterShouldNotBeCalled()
        {
            var searchParameter = new SearchParameter()
            {
                Id = "Id"
            };
            var resource = searchParameter.ToTypedElement().ToResourceElement();

            var key     = new ResourceKey("SearchParameter", "Id");
            var request = new DeleteResourceRequest(key, DeleteOperation.SoftDelete);
            var wrapper = CreateResourceWrapper(resource, true);

            _fhirDataStore.GetAsync(key, Arg.Any <CancellationToken>()).Returns(wrapper);

            var response = new DeleteResourceResponse(key);

            var behavior = new DeleteSearchParameterBehavior <DeleteResourceRequest, DeleteResourceResponse>(_searchParameterOperations, _fhirDataStore);
            await behavior.Handle(request, CancellationToken.None, async() => await Task.Run(() => response));

            await _searchParameterOperations.DidNotReceive().DeleteSearchParameterAsync(Arg.Any <RawResource>(), Arg.Any <CancellationToken>());
        }
        /// <summary>
        /// Sets the activated state of the margin.
        /// </summary>
        /// <param name="marginIsActivated">The new activated state to assign to the margin.</param>
        private void SetMarginActivated(bool marginIsActivated)
        {
            if (_isActivated == marginIsActivated)
            {
                return;
            }

            _isActivated = marginIsActivated;
            Debug.WriteLine(string.Format("MarginActivity: {0} ({1})", marginIsActivated, _textDoc.FilePath), Properties.Resources.ProductName);

            if (marginIsActivated)
            {
                _textView.LayoutChanged         += OnTextViewLayoutChanged;
                _textView.ZoomLevelChanged      += OnTextViewZoomLevelChanged;
                _textDoc.FileActionOccurred     += OnTextDocFileActionOccurred;
                _formatMap.FormatMappingChanged += OnFormatMapFormatMappingChanged;
                TfsPendingChangesMarginPackage.GeneralSettingsChanged += OnGeneralSettingsChanged;
                _versionControl.CommitCheckin += OnVersionControlCommitCheckin;
                _scrollMap.MappingChanged     += OnScrollMapMappingChanged;

                _versionControlItemWatcherCts = new CancellationTokenSource();
                CancellationToken token = _versionControlItemWatcherCts.Token;
                _versionControlItemWatcher = Task.Run(async() => await ObserveVersionControlItem(token), token);
            }
            else
            {
                _textView.LayoutChanged         -= OnTextViewLayoutChanged;
                _textView.ZoomLevelChanged      -= OnTextViewZoomLevelChanged;
                _textDoc.FileActionOccurred     -= OnTextDocFileActionOccurred;
                _formatMap.FormatMappingChanged -= OnFormatMapFormatMappingChanged;
                TfsPendingChangesMarginPackage.GeneralSettingsChanged -= OnGeneralSettingsChanged;
                _versionControl.CommitCheckin -= OnVersionControlCommitCheckin;
                _scrollMap.MappingChanged     -= OnScrollMapMappingChanged;

                if (_versionControlItemWatcherCts != null)
                {
                    _versionControlItemWatcherCts.Cancel();
                }
            }
        }
        public TestContainerDiscoverer
        (
            [Import(typeof(IOperationState))]
            IOperationState operationState,

            IFCCEngine fccEngine,
            IInitializer initializer,
            ITestOperationFactory testOperationFactory,
            ILogger logger,
            IAppOptionsProvider appOptionsProvider,
            IReportGeneratorUtil reportGeneratorUtil,
            IDisposeAwareTaskRunner disposeAwareTaskRunner,
            IMsCodeCoverageRunSettingsService msCodeCoverageRunSettingsService

        )
        {
            this.appOptionsProvider  = appOptionsProvider;
            this.reportGeneratorUtil = reportGeneratorUtil;
            this.msCodeCoverageRunSettingsService = msCodeCoverageRunSettingsService;
            this.fccEngine            = fccEngine;
            this.testOperationFactory = testOperationFactory;
            this.logger = logger;
            testOperationStateChangeHandlers = new Dictionary <TestOperationStates, Func <IOperation, Task> >
            {
                { TestOperationStates.TestExecutionCanceling, TestExecutionCancellingAsync },
                { TestOperationStates.TestExecutionStarting, TestExecutionStartingAsync },
                { TestOperationStates.TestExecutionFinished, TestExecutionFinishedAsync },
                { TestOperationStates.TestExecutionCancelAndFinished, TestExecutionCancelAndFinishedAsync },
            };

            disposeAwareTaskRunner.RunAsync(() =>
            {
                initializeTask = Task.Run(async() =>
                {
                    operationState.StateChanged += OperationState_StateChanged;
                    await initializer.InitializeAsync(disposeAwareTaskRunner.DisposalToken);
                });
                return(initializeTask);
            });
        }
        private Task ConvertPdb2MdbAsync(string outputDirectory, Action <string> msgOutput)
        {
            return(Task.Run(() =>
            {
                msgOutput?.Invoke($"Start ConvertPdb2Mdb: {outputDirectory} ...");

                var assemblyFiles = Directory.EnumerateFiles(outputDirectory, "*.exe", SearchOption.AllDirectories)
                                    .Union(Directory.EnumerateFiles(outputDirectory, "*.dll", SearchOption.AllDirectories));

                foreach (string file in assemblyFiles)
                {
                    var pdbFile = Path.ChangeExtension(file, "pdb");
                    if (!File.Exists(pdbFile))
                    {
                        // No *.pdb file found for file
                        continue;
                    }

                    var mdbFile = file + ".mdb";
                    if (File.GetLastWriteTime(pdbFile) <= File.GetLastWriteTime(mdbFile))
                    {
                        // No newer *.pdb file found
                        msgOutput?.Invoke($"No mdb file creation needed for {file}. (*.pdb file write time <= *.mdb file write time)");
                        continue;
                    }

                    msgOutput?.Invoke($"Creating mdb file for {file}");
                    try
                    {
                        Pdb2Mdb.Converter.Convert(file);
                    }
                    catch (Exception ex)
                    {
                        msgOutput?.Invoke($"Error while creating mdb file for {file}. {ex.Message}");
                    }
                }

                msgOutput?.Invoke($"End ConvertPdb2Mdb.");
            }));
        }
Beispiel #9
0
 private void Execute(object sender, EventArgs e)
 {
     if (!Generator.IsGenerating)
     {
         _ = Task.Run(async() =>
         {
             Search();
             if (await Generator.ExecuteAsync(VsSolution.SolutionExplorer.CurrentSelectedOpenApiDocItem))
             {
                 DisplayMessage("Code generator successful.");
             }
             else
             {
                 DisplayMessage("Code generator failed.");
             }
         });
     }
     else
     {
         DisplayMessage("Code generator is still executing, please wait.");
     }
 }
        public override bool Execute()
        {
            for (int i = 0; i < SourceFiles.Length; ++i)
            {
                var sf = SourceFiles [i];
                var rp = sf.GetMetadata("DestDir");
                rp = string.IsNullOrEmpty(rp)
                                        ? ""
                                        : " [ " + rp + " ]";
                Log.LogMessage(MessageImportance.Low, "    {0}{1}", sf, rp);
            }

            if (File.Exists(DestinationFolder.ItemSpec))
            {
                Log.LogError("DestinationFolder must be a directory!");
                return(false);
            }

            Directory.CreateDirectory(DestinationFolder.ItemSpec);

            var encoding = string.IsNullOrEmpty(EntryNameEncoding)
                                ? null
                                : Encoding.GetEncoding(EntryNameEncoding);

            var tasks = new TTask [SourceFiles.Length];

            for (int i = 0; i < SourceFiles.Length; ++i)
            {
                var sourceFile      = SourceFiles [i];
                var relativeDestDir = sourceFile.GetMetadata("DestDir");
                var enc             = encoding;
                var destFolder      = DestinationFolder.ItemSpec;
                tasks [i] = TTask.Run(() => ExtractFile(sourceFile.ItemSpec, relativeDestDir, destFolder, enc));
            }

            TTask.WaitAll(tasks);

            return(!Log.HasLoggedErrors);
        }
        private async Task InitializeAsync()
        {
            await Task.Run(() =>
            {
                CommandID menuCommandID = new CommandID(CommandSet, RestartId);
                OleMenuCommand menuItem = new OleMenuCommand(MenuItemCallback, menuCommandID);
                //menuItem.BeforeQueryStatus += OnBeforeQueryStatus;
                CommandService.AddCommand(menuItem);

                CommandID restartElevatedCommandID     = new CommandID(CmdsGroupSet, RestartAsAdministratorId);
                OleMenuCommand restartElevatedMenuItem = new OleMenuCommand(MenuItemCallback, restartElevatedCommandID);
                //restartElevatedMenuItem.BeforeQueryStatus += OnBeforeQueryStatus;
                CommandService.AddCommand(restartElevatedMenuItem);
                restartElevatedMenuItem.Enabled = !IsRunningElevated;

                CommandID restartCommandID     = new CommandID(CmdsGroupSet, RestartAsUserId);
                OleMenuCommand restartMenuItem = new OleMenuCommand(MenuItemCallback, restartCommandID);
                //restartMenuItem.BeforeQueryStatus += OnBeforeQueryStatus;
                CommandService.AddCommand(restartMenuItem);
                restartMenuItem.Enabled = IsRunningElevated;
            });
        }
        protected override void ProcessRecordCore()
        {
            var startTime = DateTimeOffset.Now;

            _packageCount = 1;

            // Enable granular level events for this uninstall operation
            TelemetryService = new TelemetryServiceHelper();
            TelemetryUtility.StartorResumeTimer();

            // Run Preprocess outside of JTF
            Preprocess();

            NuGetUIThreadHelper.JoinableTaskFactory.Run(async() =>
            {
                await _lockService.ExecuteNuGetOperationAsync(() =>
                {
                    SubscribeToProgressEvents();
                    Task.Run(UninstallPackageAsync);
                    WaitAndLogPackageActions();
                    UnsubscribeFromProgressEvents();

                    return(Task.FromResult(true));
                }, Token);
            });

            TelemetryUtility.StopTimer();
            var actionTelemetryEvent = TelemetryUtility.GetActionTelemetryEvent(
                new[] { Project },
                NuGetOperationType.Uninstall,
                OperationSource.PMC,
                startTime,
                _status,
                _packageCount,
                TelemetryUtility.GetTimerElapsedTimeInSeconds());

            // emit telemetry event with granular level events
            ActionsTelemetryService.Instance.EmitActionEvent(actionTelemetryEvent, TelemetryService.TelemetryEvents);
        }
Beispiel #13
0
        private List <Compilation> GetCompilations()
        {
            var compilations = new List <Compilation>();

            foreach (var p in Workspace.CurrentSolution.Projects)
            {
                try
                {
                    var compilation = Task.Run(() => p.GetCompilationAsync()).Result;
                    if (compilation != null)
                    {
                        compilations.Add(compilation);
                    }
                }
                catch (Exception ex)
                {
                    LogService.LogError(new Exception("Cannot get the compilation!", ex));
                }
            }

            return(compilations);
        }
        internal static Task LoadTask() =>
        TaskEx.Run(() =>
        {
            YeetIfNeeded();

            var sw = Stopwatch.StartNew();

            LoadMetadata();

            sw.Stop();
            Logger.Loader.Info($"Loading metadata took {sw.Elapsed}");
            sw.Reset();

            sw.Start();

            // Features contribute to load order considerations
            InitFeatures();
            DoOrderResolution();

            sw.Stop();
            Logger.Loader.Info($"Calculating load order took {sw.Elapsed}");
        });
        private async Task RequestFeeds(string feedSource)
        {
            try
            {
                await Task.Run(() => GetFeeds(feedSource));
            }
            catch (Exception ex) when(!ExceptionExtensions.IsCriticalException(ex))
            {
                MessageBox.Show(SR.GetString(SR.WebPiFeedError, feedSource, ex.Message));

                var fullMessage = SR.GetString(SR.WebPiFeedError, feedSource, ex);

                Trace.WriteLine(fullMessage);
                try
                {
                    ActivityLog.LogError("WebPiComponentPickerControl", fullMessage);
                }
                catch (InvalidOperationException)
                {
                }
            }
        }
Beispiel #16
0
        private void RebuildCoverage(ITextSnapshot snapshotObject, string documentName)
        {
            try
            {
                _IsRebuilding = true;
                _documentName = documentName;
                _log.DebugFormat("RebuildCoverage - Document: {0}", documentName);
                ITextSnapshot snapshot = snapshotObject;

                if (_dte != null && _dte.ActiveDocument != null)
                {
                    FileCodeModel fcm = GetFileCodeModel(documentName);
                    if (fcm == null)
                    {
                        _log.DebugFormat("ERROR File Code Model is null for Project Item:{0}",
                                         _dte.ActiveDocument.ProjectItem);
                        _IsRebuilding = false;
                    }
                    else
                    {
                        if (_HasCoveredLinesBeenInitialized)
                        {
                            Task.Run(() => GetCoveredLinesFromCodeModel(fcm));
                        }
                        else
                        {
                            GetCoveredLinesFromCodeModel(fcm);
                        }
                    }

                    _currentVersion = snapshot.Version.VersionNumber;
                }
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Error RebuildingCoveredLines Error: {0} StackTrace: {1} InnerException: {2}",
                                 ex.Message, ex.StackTrace, ex.InnerException);
            }
        }
Beispiel #17
0
        private static int heartbeatFrequency = 2; // minutes
        #endregion

        #region Startup/Cleanup
        protected override void Initialize()
        {
            base.Initialize();

            ObjDte     = (DTE2)GetService(typeof(DTE));
            _dteEvents = ObjDte.Events.DTEEvents;
            _dteEvents.OnStartupComplete += OnOnStartupComplete;

            if (DisableThreading)
            {
                Logger.Debug("Initializing without threading.");
                InitializeAsync();
            }
            else
            {
                Logger.Debug("Initializing in background thread.");
                Task.Run(() =>
                {
                    InitializeAsync();
                });
            }
        }
Beispiel #18
0
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (Package.GetGlobalService(typeof(SDTE)) is DTE dte && (dte.ActiveSolutionProjects is Array projects && projects.Length > 0))
            {
                var activeProject = projects.GetValue(0) as Project;
                if (activeProject != null)
                {
                    var parameters = CreateBuildParameters();
                    var data       = CreateBuildRequestData(activeProject, "SyncUnicorn", dte);

                    Task.Run(() =>
                    {
                        using (var buildManager = new BuildManager())
                        {
                            buildManager.Build(parameters, data);
                        }
                    });
                }
            }
        }
Beispiel #19
0
        protected override void ProcessRecordCore()
        {
            var startTime = DateTimeOffset.Now;

            _packageCount = 1;

            var stopWatch = Stopwatch.StartNew();

            // Run Preprocess outside of JTF
            Preprocess();

            NuGetUIThreadHelper.JoinableTaskFactory.Run(async() =>
            {
                await _lockService.ExecuteNuGetOperationAsync(() =>
                {
                    SubscribeToProgressEvents();
                    Task.Run(UninstallPackageAsync);
                    WaitAndLogPackageActions();
                    UnsubscribeFromProgressEvents();

                    return(Task.FromResult(true));
                }, Token);
            });

            stopWatch.Stop();
            var actionTelemetryEvent = VSTelemetryServiceUtility.GetActionTelemetryEvent(
                OperationId.ToString(),
                new[] { Project },
                NuGetOperationType.Uninstall,
                OperationSource.PMC,
                startTime,
                _status,
                _packageCount,
                stopWatch.Elapsed.TotalSeconds);

            // emit telemetry event along with granular level events
            TelemetryActivity.EmitTelemetryEvent(actionTelemetryEvent);
        }
Beispiel #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SearchResultTableDataSource"/> class.
        /// </summary>
        /// <param name="collection">The collection.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        public SearchResultTableDataSource(IProducerConsumerCollection <IEnumerable <SearchResult> > collection, CancellationToken cancellationToken)
        {
            var blocking = new BlockingCollection <IEnumerable <SearchResult> >(collection);

            Task.Run(() => {
                try {
                    foreach (var item in blocking.GetConsumingEnumerable(cancellationToken))
                    {
                        var entries = item
                                      .Select(x => new TableEntry(x))
                                      .ToList()
                                      .AsReadOnly();

                        foreach (var sink in _sinks)
                        {
                            sink.AddEntries(entries);
                        }
                    }
                }
                catch (OperationCanceledException) {
                }
            });
        }
Beispiel #21
0
        public void ProjectFinishedGenerating(Project project)
        {
            var projectPath = project.FullName.Substring(0,
                                                         project.FullName.LastIndexOf("\\", StringComparison.Ordinal));

            Task.Run(() => { StartRequiredPackageInstallations(); }).Wait();
            // Typings isn't supported by any built in VS features.. yet.., run manually and wait
            // This is due to problem with TSX intellisense which is fixed if project reloaded.
            // This is to ensure *.d.ts files are ready when template first loads
            Task.Run(() => { ProcessTypingsInstall(projectPath); }).Wait();
            //Only run Bower/NPM install via SSVS for VS 2012/2013
            //VS2015 built in Task Runner detects and runs required installs.
            //VS2013 Update 5 also does package restore on load.
            if (MajorVisualStudioVersion == 12 && !ExtensionManager.HasExtension("Package Intellisense") || MajorVisualStudioVersion == 11)
            {
                Task.Run(() => { ProcessBowerInstall(projectPath); }).Wait();

                UpdateStatusMessage("Downloading NPM depedencies...");
                OutputWindowWriter.ShowOutputPane(_dte);

                Task.Run(() => { ProcessNpmInstall(projectPath); });
            }
        }
Beispiel #22
0
        private async void InitStart()
        {
            InitData initData = new InitData();
            await Task.Run(() =>
            {
                Progres.Visible = false;

                Application.Invoke(delegate
                                   { textView.Buffer.Text = LoadingHistory.Loading(); });



                initData = Settings.SettingsFileRead().Result;
            });



            if (initData != null)
            {
                Application.Invoke(delegate
                                   { Entry.Text = initData.Currency + initData.Address; });
            }
        }
        public void QuerySingleAsyncOperator_With0Results_ShouldThrowInvalidOperationException()
        {
            var cases = new List <Case>();

            _objectModelAdapterMock.StubQueryAsync().Return(Task.Run <IEnumerable <object> >(() => cases));

            var ephorteContext = CreateAsyncEphorteContextWithObjectModelAdapter();

            try
            {
#pragma warning disable 168
                var result = ephorteContext.Query <Case>().SingleAsync().Result;
#pragma warning restore 168
                Assert.Fail();
            }
            catch (AggregateException e)
            {
                if (e.InnerException.GetType() != typeof(InvalidOperationException))
                {
                    Assert.Fail();
                }
            }
        }
Beispiel #24
0
        private void UpdateNoti()
        {
            try
            {
                Task.Run(() =>
                {
                    try
                    {
                        string songName   = Methods.FunString.DecodeString(Constant.ArrayListPlay[Constant.PlayPos]?.Title);
                        string genresName = Methods.FunString.DecodeString(Constant.ArrayListPlay[Constant.PlayPos]?.CategoryName) + " " + GlobalContext.GetText(Resource.String.Lbl_Music);

                        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                        {
                            Notification.SetContentTitle(songName);
                            Notification.SetContentText(genresName);
                        }
                        else
                        {
                            BigViews.SetTextViewText(Resource.Id.textView_noti_name, songName);
                            BigViews.SetTextViewText(Resource.Id.textView_noti_artist, genresName);
                            SmallViews.SetTextViewText(Resource.Id.status_bar_artist_name, genresName);
                            SmallViews.SetTextViewText(Resource.Id.status_bar_track_name, songName);
                        }

                        UpdateNotiPlay(Constant.Player.PlayWhenReady);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Beispiel #25
0
        protected override async Task InitializeAsync(
            CancellationToken cancellationToken,
            IProgress <ServiceProgressData> progress)
        {
            // Get package install path
            var uri = new Uri(System.Reflection.Assembly
                              .GetExecutingAssembly().EscapedCodeBase);
            var pkgInstallPath = Path.GetDirectoryName(
                Uri.UnescapeDataString(uri.AbsolutePath)) + @"\";

            // Install client interface
            var qtVsTestFiles = Environment.
                                ExpandEnvironmentVariables(@"%LOCALAPPDATA%\qtvstest");

            Directory.CreateDirectory(qtVsTestFiles);
            File.Copy(
                Path.Combine(pkgInstallPath, "MacroClient.h"),
                Path.Combine(qtVsTestFiles, "MacroClient.h"),
                overwrite: true);

            // Install .csmacro syntax highlighting
            var grammarFilesPath = Environment.
                                   ExpandEnvironmentVariables(@"%USERPROFILE%\.vs\Extensions\qtcsmacro");

            Directory.CreateDirectory(grammarFilesPath);
            File.Copy(
                Path.Combine(pkgInstallPath, "csmacro.tmLanguage"),
                Path.Combine(grammarFilesPath, "csmacro.tmLanguage"),
                overwrite: true);
            File.Copy(
                Path.Combine(pkgInstallPath, "csmacro.tmTheme"),
                Path.Combine(grammarFilesPath, "csmacro.tmTheme"),
                overwrite: true);

            // Start macro server loop as background task
            await Task.Run(() => MacroServer.LoopAsync().Forget());
        }
Beispiel #26
0
        private async void BackgroundTaskProcess()
        {
            int i = 0;

            while (!_token.IsCancellationRequested)
            {
                await BackgroundTask.Run(() => LoadNewModules());

                for (int j = 0; j < 10; j++)
                {
                    Thread.Sleep(500);
                    if (_token.IsCancellationRequested)
                    {
                        break;
                    }
                }

                if (_token.IsCancellationRequested)
                {
                    break;
                }
                i++;
            }
        }
Beispiel #27
0
        private void OnLineChanged(TextPoint startPoint, TextPoint endPoint, int Hint)
        {
            var changedText = GetChangedText(startPoint, endPoint);

            if (changedText.Length != 0 && IsLastModifiedCharacterPeriod(changedText))
            {
                CancelPreviousSaveTask();
                return;
            }

            CancelPreviousSaveTask();

            var _cancellationTokenSource = new CancellationTokenSource();

            _stack.Push(_cancellationTokenSource);

            Task.Run(async() =>
            {
                try
                {
                    await WaitForUserConfiguredDelayAsync();

                    var dte        = (DTE)await this.GetServiceAsync(typeof(DTE));
                    var windowType = dte.ActiveWindow.Kind;

                    if (!_cancellationTokenSource.IsCancellationRequested)
                    {
                        SaveDocument(dte, windowType);
                    }
                }
                catch (Exception exception)
                {
                    GetLogger().LogError(GetPackageName(), "Exception during line change event handling", exception);
                }
            });
        }
Beispiel #28
0
        protected override void Initialize()
        {
            base.Initialize();

            // Load config file
            Config = new ConfigFile();
            Config.Read();

            ObjDte     = (DTE)GetService(typeof(DTE));
            _dteEvents = ObjDte.Events.DTEEvents;

            _isAsyncLoadSupported = this.IsAsyncPackageSupported();

            // Only perform initialization if async package framework not supported
            if (!_isAsyncLoadSupported)
            {
                // Try force initializing in brackground
                Logger.Debug("Initializing in background thread.");
                Task.Run(() =>
                {
                    InitializeAsync();
                });
            }
        }
Beispiel #29
0
        public void DoingInThreadPool(
            Action doAction
            )
        {
            if (doAction is null)
            {
                throw new ArgumentNullException(nameof(doAction));
            }

            try
            {
                Task.Run(() =>
                {
                    lock (_locker)
                    {
                        doAction();
                    }
                }).FileAndForget(nameof(DoingInThreadPool));
            }
            catch (Exception excp)
            {
                LogVS(excp);
            }
        }
Beispiel #30
0
        private void bt_Connection_Click(Object sender, EventArgs e)
        {
            SaveConfig();

            if (bt_Connection.Text == "连接")
            {
                //Engine = null;
                LoadTables();

                gbConnect.Enabled              = false;
                gbTable.Enabled                = true;
                模型ToolStripMenuItem.Visible    = true;
                架构管理SToolStripMenuItem.Visible = true;
                //btnImport.Enabled = false;
                btnImport.Text          = "导出模型";
                bt_Connection.Text      = "断开";
                btnRefreshTable.Enabled = true;
            }
            else
            {
                SetTables(null);

                gbConnect.Enabled              = true;
                gbTable.Enabled                = false;
                模型ToolStripMenuItem.Visible    = false;
                架构管理SToolStripMenuItem.Visible = false;
                btnImport.Enabled              = true;
                btnImport.Text          = "导入模型";
                bt_Connection.Text      = "连接";
                btnRefreshTable.Enabled = false;
                //Engine = null;

                // 断开的时候再取一次,确保下次能及时得到新的
                TaskEx.Run(() => DAL.Create(Config.ConnName).Tables);
            }
        }