예제 #1
0
        public CallAsyncOp(model.WebSvcMethod webSvcMethod, CancelToken cancelToken, int timeoutPeriod, model.IProxy proxy, ILog log)
            : base(webSvcMethod.Name, timeoutPeriod, proxy, log)
        {
            _webSvcMethod = webSvcMethod;
            _cancelToken = cancelToken;

            _cancelObject = new process.WebSvcAsync.CancelObject(webSvcMethod.Name, cancelToken);
            _cancelObject.OnCancel += _cancelObject_OnCancel;
        }
예제 #2
0
        public async Task <IList <DbFolder> > GetAllFolders(CancelToken cancelToken = null)
        {
            const string sql = @"
                SELECT id, name, parent_id
                FROM folders
                ORDER BY id;
            ";

            SQLiteConnection connection = await GetConnection(Path);

            try
            {
                if (cancelToken?.IsCanceled == true)
                {
                    return(null);
                }

                using (DbDataReader reader = await connection.ExecuteReaderAsync(sql))
                {
                    if (cancelToken?.IsCanceled == true)
                    {
                        return(null);
                    }

                    int idIndex       = reader.GetOrdinal("id");
                    int nameIndex     = reader.GetOrdinal("name");
                    int parentIdIndex = reader.GetOrdinal("parent_id");

                    List <DbFolder> folders = new List <DbFolder>();
                    while (await reader.ReadAsync())
                    {
                        if (cancelToken?.IsCanceled == true)
                        {
                            return(null);
                        }

                        long   id       = reader.GetInt64(idIndex);
                        string name     = reader.GetString(nameIndex);
                        long?  parentId = reader.IsDBNull(parentIdIndex) ? (long?)null : reader.GetInt64(parentIdIndex);
                        folders.Add(new DbFolder(id, parentId, name));
                    }

                    return(folders);
                }
            }
            finally
            {
                ReleaseConnection();
            }
        }
예제 #3
0
        public IHttpActionResult DeleteCancelToken(int id)
        {
            CancelToken cancelToken = db.CancelTokens.Find(id);

            if (cancelToken == null)
            {
                return(NotFound());
            }

            db.CancelTokens.Remove(cancelToken);
            db.SaveChanges();

            return(Ok(cancelToken));
        }
예제 #4
0
        private async Task BeginConnect(string email, string password, string token = null)
        {
            try
            {
                using (await _connectionLock.LockAsync().ConfigureAwait(false))
                {
                    await Disconnect().ConfigureAwait(false);

                    _taskManager.ClearException();

                    Stopwatch stopwatch = null;
                    if (Config.LogLevel >= LogSeverity.Verbose)
                    {
                        _connectionStopwatch.Restart();
                        stopwatch = Stopwatch.StartNew();
                    }
                    State = ConnectionState.Connecting;
                    _disconnectedEvent.Reset();

                    var cancelSource = new CancellationTokenSource();
                    CancelToken           = cancelSource.Token;
                    ClientAPI.CancelToken = CancelToken;
                    StatusAPI.CancelToken = CancelToken;

                    await Login(email, password, token).ConfigureAwait(false);

                    await GatewaySocket.Connect(ClientAPI, CancelToken).ConfigureAwait(false);

                    var tasks = new[] { CancelToken.Wait() }
                    .Concat(MessageQueue.Run(CancelToken));

                    await _taskManager.Start(tasks, cancelSource).ConfigureAwait(false);

                    GatewaySocket.WaitForConnection(CancelToken);

                    if (Config.LogLevel >= LogSeverity.Verbose)
                    {
                        stopwatch.Stop();
                        double seconds = Math.Round(stopwatch.ElapsedTicks / (double)TimeSpan.TicksPerSecond, 2);
                        Logger.Verbose($"Handshake + Ready took {seconds} sec");
                    }
                }
            }
            catch (Exception ex)
            {
                await _taskManager.SignalError(ex).ConfigureAwait(false);

                throw;
            }
        }
            private async Task Input()
            {
                await Task.Factory.StartNew(async() =>
                {
                    scans = new List <List <ScannedImage> >();

                    switch (Settings.ScanType)
                    {
                    case BatchScanType.Single:
                        await InputOneScan(-1);
                        break;

                    case BatchScanType.MultipleWithDelay:
                        {
                            for (var i = 0; i < Settings.ScanCount; i++)
                            {
                                ProgressCallback(string.Format(MiscResources.BatchStatusWaitingForScan, i + 1));
                                if (i != 0)
                                {
                                    ThreadSleepWithCancel(TimeSpan.FromSeconds(Settings.ScanIntervalSeconds), CancelToken);
                                    CancelToken.ThrowIfCancellationRequested();
                                }

                                if (!await InputOneScan(i))
                                {
                                    return;
                                }
                            }

                            break;
                        }

                    case BatchScanType.MultipleWithPrompt:
                        {
                            var i = 0;
                            do
                            {
                                ProgressCallback(string.Format(MiscResources.BatchStatusWaitingForScan, i + 1));
                                if (!await InputOneScan(i++))
                                {
                                    return;
                                }
                                CancelToken.ThrowIfCancellationRequested();
                            } while (PromptForNextScan());

                            break;
                        }
                    }
                }, TaskCreationOptions.LongRunning).Unwrap();
            }
        public void ThrowIfAnyParametersInvalid()
        {
            if (DataPersistenceLayer == null)
            {
                throw new ArgumentException(nameof(DataPersistenceLayer));
            }
            if (ReportExceptionFunction == null)
            {
                throw new ArgumentNullException(nameof(ReportExceptionFunction));
            }
            if (ReportOutputFunction == null)
            {
                throw new ArgumentNullException(nameof(ReportOutputFunction));
            }
            if (LogOutputFunction == null)
            {
                throw new ArgumentNullException(nameof(LogOutputFunction));
            }
            if (ReportResultsFunction == null)
            {
                throw new ArgumentNullException(nameof(ReportResultsFunction));
            }
            if (string.IsNullOrWhiteSpace(SelectedFolder))
            {
                throw new ArgumentNullException(nameof(SelectedFolder));
            }
            if (!Directory.Exists(SelectedFolder))
            {
                throw new DirectoryNotFoundException(SelectedFolder);
            }

            char suppliedDriveLetter = char.ToUpper(SelectedFolder[0]);

            List <char> foundDriveLetters = DriveInfo.GetDrives()
                                            .Where(d => d.IsReady && d.DriveFormat == "NTFS")
                                            .Select(di => di.Name.ToUpper()[0])
                                            .ToList();

            if (!foundDriveLetters.Any() || !foundDriveLetters.Contains(suppliedDriveLetter))
            {
                throw new DriveNotFoundException($"The drive {suppliedDriveLetter}:\\ was not found, the drive was not mounted or ready, or the drive had a file system other than NTFS.");
            }

            if (CancelToken == null)
            {
                throw new ArgumentNullException(nameof(CancelToken), "If you do not want to pass a CancellationToken, then pass 'CancellationToken.None'");
            }
            CancelToken.ThrowIfCancellationRequested();
        }
예제 #7
0
        public TaskBackupItem(string name, string filesDestFolderPath, Folder folder,
                              PathPattern[] excludePatterns, IList <string> addedFiles, CancelToken cancelToken)
        {
            addedToDbFolders      = new List <DbFolder>();
            addedToDbFiles        = new List <DbFile>();
            addedToDbFoldersFiles = new List <DbFolderFile>();
            allFiles = new List <BackupFile>();

            Name = name;
            FilesDestFolderPath = filesDestFolderPath;
            Folder           = folder;
            ExcludePatterns  = excludePatterns;
            this.addedFiles  = addedFiles;
            this.cancelToken = cancelToken;
        }
예제 #8
0
        /// <summary>
        /// Cancels this instance.
        /// </summary>
        private void Cancel()
        {
            lock (_cancelSync)
            {
                CancelToken?.Cancel();
            }

            //wait for the current process to finish. It should be respecting the cancel
            //token, so it should not take long.
            while (Running)
            {
                Thread.Sleep(20);
            }

            CancelTokenDestroy();
        }
예제 #9
0
        void AsyncCalculateStatus(CancelToken cancelToken)
        {
            Dictionary <string, AssetStatus> statusByPathCache = null;

            IThreadWaiter waiter = ThreadWaiter.GetWaiter(50);

            waiter.Execute(
                /*threadOperationDelegate*/ delegate
            {
                OutOfDateItems outOfDateItems =
                    OutOfDateUpdater.CalculateOutOfDateItems(
                        mWkInfo, new List <ErrorMessage>(),
                        OutOfDateCalculator.Options.IsIncomingChanges);

                if (cancelToken.IsCancelled())
                {
                    return;
                }

                statusByPathCache = BuildStatusByPathCache.
                                    ForOutOfDateItems(outOfDateItems, mWkInfo.ClientPath);
            },
                /*afterOperationDelegate*/ delegate
            {
                if (waiter.Exception != null)
                {
                    ExceptionsHandler.LogException(
                        "RemoteStatusCache",
                        waiter.Exception);
                    return;
                }

                if (cancelToken.IsCancelled())
                {
                    return;
                }

                lock (mLock)
                {
                    mStatusByPathCache = statusByPathCache;
                }

                mRepaintProjectWindow();
            });
        }
예제 #10
0
        public bool Is(int argCount, Func <LinkedListNode <Token>, LinkedListNode <Token> > argGetNode, Func <Token, bool> argCond)
        {
            var pNode = NodeAct;

            for (var i = 0; i < argCount; i++)
            {
                CancelToken.ThrowIfCancellationRequested();

                if (pNode == null || !argCond.Invoke(pNode.Value))
                {
                    return(false);
                }

                pNode = argGetNode(pNode);
            }

            return(true);
        }
예제 #11
0
 protected override async Task ScanInternal(ScannedImageSource.Concrete source)
 {
     await Task.Factory.StartNew(async() =>
     {
         if (UseWorker)
         {
             var parentHandle = DialogParent?.SafeHandle() ?? IntPtr.Zero;
             try
             {
                 using (var worker = workerServiceFactory.Create())
                 {
                     worker.Callback.ImageCallback += (img, tempPath) =>
                     {
                         if (tempPath != null)
                         {
                             scannedImageHelper.RunBackgroundOcr(img, ScanParams, tempPath);
                         }
                         source.Put(img);
                     };
                     CancelToken.Register(worker.Service.CancelTwainScan);
                     await worker.Service.TwainScan(ScanDevice, ScanProfile, ScanParams, parentHandle);
                 }
             }
             finally
             {
                 if (parentHandle != IntPtr.Zero)
                 {
                     // If the worker process hard crashes while a modal window is open, it may leave the parent
                     // window in a state where it can't be interacted with. This fixes that interaction.
                     //
                     // At the Windows API level, a modal window is implemented by doing two things:
                     // 1. Setting the parent on the child window
                     // 2. Disabling the parent window
                     // The first is implicitly undone when the worker process dies. The second is undone here.
                     Win32.EnableWindow(parentHandle, true);
                 }
             }
         }
         else
         {
             twainWrapper.Scan(DialogParent, ScanDevice, ScanProfile, ScanParams, CancelToken, source, scannedImageHelper.RunBackgroundOcr);
         }
     }, TaskCreationOptions.LongRunning).Unwrap();
 }
예제 #12
0
        private async Task ProcessSocketData()
        {
            IsRunning = true;

            // Buffers for received data
            var receivedMessage = new List <byte>();
            var buffer          = new byte[9192];

            while (true)
            {
                try
                {
                    // Get data until the complete message is received
                    WebSocketReceiveResult response;
                    do
                    {
                        response = await _client.ReceiveAsync(new ArraySegment <byte>(buffer), CancelToken);

                        if (response.CloseStatus != null)
                        {
                            throw new Exception(response.CloseStatusDescription);
                        }
                        var segment = new ArraySegment <byte>(buffer, 0, response.Count);
                        receivedMessage.AddRange(segment);
                    } while (!response.EndOfMessage);

                    // Decode the message
                    var messageJson = Encoding.ASCII.GetString(receivedMessage.ToArray());
                    receivedMessage.Clear();

                    // Parse and notify subscriber
                    var data = JsonConvert.DeserializeObject <TResponse>(messageJson);
                    OnData(_api, data);
                }
                catch (OperationCanceledException) { }

                if (CancelToken.IsCancellationRequested)
                {
                    IsRunning = false;
                    CancelToken.ThrowIfCancellationRequested();
                }
            }
        }
        public void CancelRequest()
        {
            try
            {
#if DOT_NET
                // kill the task - we've timed out
                IsCancelled = true;
                if (WebRequest != null)
                {
                    CancelToken.Cancel();
                }
#else
                CleanupRequest();
#endif
            }
            catch (Exception)
            {
            }
        }
예제 #14
0
        void RouteGraphEdgesAsSplines()
        {
            var geomGraph      = gViewer.Graph.GeometryGraph;
            var layoutSettings = gViewer.Graph.LayoutAlgorithmSettings;
            EdgeRoutingSettings routingSettings = layoutSettings.EdgeRoutingSettings;

            if (routingSettings.EdgeRoutingMode == EdgeRoutingMode.StraightLine)
            {
                RouteStraightLines();
            }
            else
            if (routingSettings.EdgeRoutingMode == EdgeRoutingMode.Spline)
            {
                var coneAngle = routingSettings.ConeAngle;
                var padding   = layoutSettings.NodeSeparation * gViewer.TightOffsetForRouting * 2;
                this.currentCancelToken = new CancelToken();
                var router = new SplineRouter(geomGraph, padding, 0.65 * padding, coneAngle, null);
                router.Run(this.currentCancelToken);
            }
            else if (routingSettings.EdgeRoutingMode == EdgeRoutingMode.SplineBundling)
            {
                var coneAngle    = routingSettings.ConeAngle;
                var padding      = layoutSettings.NodeSeparation / 3;
                var loosePadding = SplineRouter.ComputeLooseSplinePadding(layoutSettings.NodeSeparation, padding);
                if (layoutSettings.EdgeRoutingSettings.BundlingSettings == null)
                {
                    layoutSettings.EdgeRoutingSettings.BundlingSettings = new BundlingSettings();
                }
                var br = new SplineRouter(geomGraph, padding, loosePadding, coneAngle, layoutSettings.EdgeRoutingSettings.BundlingSettings);
                br.Run();
            }
            else
            {
                MessageBox.Show(String.Format("Mode {0} is not supported with this settings",
                                              routingSettings.EdgeRoutingMode));
                return;
            }

            new EdgeLabelPlacement(geomGraph).Run();

            InvalidateEdges();
        }
예제 #15
0
        public async static Task <BackupedFiles> GetBackupedFiles(string folderPath, CancelToken cancelToken = null)
        {
            IDictionary <string, string> hashes;
            IList <string> cacheDbNames;

            BackupReadDb[]       dbs     = GetReadDBs(folderPath).ToNotNull().ToArray();
            IEnumerable <string> dbNames = dbs.Select(db => Path.GetFileName(db.Path));

            if (!TryLoadLocalBackupedFilesCache(out hashes, out cacheDbNames) || !ContainsSame(cacheDbNames, dbNames))
            {
                hashes = new Dictionary <string, string>();
                await Task.WhenAll(dbs.Select(db => db.ImportAllFiles(hashes, cancelToken)));
            }

            IEnumerable <string> existingFileNames = Directory
                                                     .EnumerateFiles(GetBackupedFilesFolderPath(folderPath))
                                                     .Select(p => Path.GetFileName(p));

            return(new BackupedFiles(hashes, existingFileNames, dbNames));
        }
예제 #16
0
        public void DisableFutureBackups()
        {
            _updateTimerSemaphore.Wait();

            try
            {
                BackupTimer?.Dispose();
                BackupTimer = null;

                try
                {
                    CancelToken?.Cancel();
                }
                catch {}
            }
            finally
            {
                _updateTimerSemaphore.Release();
            }
        }
예제 #17
0
        internal static void OrderLayers(ProperLayeredGraph graph,
                                         LayerArrays layerArrays,
                                         int startOfVirtualNodes,
                                         SugiyamaLayoutSettings settings, CancelToken cancelToken)
        {
            bool hasCrossWeight = false;

            foreach (LayerEdge le in graph.Edges)
            {
                if (le.CrossingWeight != 1)
                {
                    hasCrossWeight = true;
                    break;
                }
            }

            var o = new Ordering(graph, true, layerArrays, startOfVirtualNodes, hasCrossWeight, settings);

            o.Run(cancelToken);
        }
예제 #18
0
        /// <summary>
        /// 异步写入单行数据, 可多次执行, 之后执行 Close 方法关闭写入流.
        /// </summary>
        /// <param name="rowData">一行数据,由字段集合组成.</param>
        /// <returns>Task</returns>
        public async Task WriteLineAsync(List <string> rowData)
        {
            if (CancelToken.IsCancellationRequested)
            {
                CancelToken.ThrowIfCancellationRequested();
            }

            if (rowData == null)
            {
                throw new ArgumentNullException(nameof(rowData));
            }

            //如果写入过一条数据, 则字段数固定. 如果再次写入的字段数不同, 报异常.
            if (columnCount > 0 && columnCount != rowData.Count)
            {
                throw new ArgumentException("the rowData count must be equal to " + columnCount.ToString());
            }

            await csvStream.WriteLineAsync(SerializeRow( rowData ));

            TotalRowCount++;

            //设置字段数
            if (columnCount == 0)
            {
                columnCount = rowData.Count;
            }

            //发送通知
            if (dataHandler != null)
            {
                //如果取余数=0, 发送通知.
                if (TotalRowCount % WriteProgressSize == 0L)
                {
                    CsvWriteProgressInfo info = new CsvWriteProgressInfo();
                    info.CurrentRowCount = WriteProgressSize;
                    info.WirteRowCount   = TotalRowCount;
                    dataHandler.Invoke(info);
                }
            }
        }
예제 #19
0
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="geometryGraph"></param>
        /// <param name="lgLayoutSettings"></param>
        /// <param name="cancelToken"></param>
        public LgInteractor(GeometryGraph geometryGraph, LgLayoutSettings lgLayoutSettings, CancelToken cancelToken)
        {
            mainGeometryGraph     = geometryGraph;
            this.lgLayoutSettings = lgLayoutSettings;
            this.cancelToken      = cancelToken;
            if (geometryGraph.LgData == null)
            {
                lgData = new LgData(geometryGraph)
                {
                    GeometryNodesToLgNodeInfos = lgLayoutSettings.GeometryNodesToLgNodeInfos
                };

                geometryGraph.LgData = lgData;
            }
            else
            {
                _initFromPrecomputedLgData = true;
                lgData = geometryGraph.LgData;
                lgLayoutSettings.GeometryNodesToLgNodeInfos = lgData.GeometryNodesToLgNodeInfos;
            }
        }
예제 #20
0
        /// <summary>
        /// 停止
        /// </summary>
        private void DoStop()
        {
            //取消
            CancelToken.Cancel();

            //停止数据泵服务
            //PumpControler.Stop();

            //停止工作线程池
            lock (WorkThreadPoolLock)
            {
                WorkThreadPool.ForEach(st => st.Stop());
                WorkThreadPool = null;
            }

            //停止后台工作主线程
            if (MainWorkThread.IsAlive)
            {
                MainWorkThread.Stop();
            }
        }
        /// <summary>Asynchronously writes the frequency and <see cref="NetworkParametersMatrix"/> the network data of the file.</summary>
        /// <param name="frequency">The frequency of the network data to be written.</param>
        /// /// <param name="matrix">The network data to be written.</param>
        /// <remarks>If <see cref="WriteHeaderAsync"/> has not yet been called, this method will be called automatically before writing any network data.</remarks>
        public async Task WriteDataAsync(double frequency, NetworkParametersMatrix matrix)
        {
            if (!headerWritten)
            {
                await WriteHeaderAsync();
            }

            CancelToken.ThrowIfCancellationRequested();

            if (settings.IncludeColumnNames && !columnsWritten)
            {
                string columns = FormatColumns(matrix.NumPorts);
                await WriteCommentLineAsync(columns);

                columnsWritten = true;

                CancelToken.ThrowIfCancellationRequested();
            }
            string line = FormatEntry(frequency, matrix);
            await Writer.WriteLineAsync(line);
        }
예제 #22
0
        public async Task <string> Convert(IWorkspace workspace, CancelToken cancelToken)
        {
            string temp     = IOUtility.GetHashFile(workspace.FileSystem.Directory, workspace.Item.FullName);
            var    settings = Settings.Default;

            if (settings.UseOfflineCompiler)
            {
                return(PandocUtility.Compile(temp, workspace.Item.FullName, settings.LocalTemplate, settings.LocalCsl, "*.md"));
            }
            else
            {
                var bytes = await workspace.ConverterService.Convert(MultipartFormParameter
                                                                     .ApiParameter(ConverterType.Markdown, ConverterType.Pdf, settings.Template, settings.Csl)
                                                                     .Concat(MultipartFormParameter
                                                                             .FromWorkspace(workspace)), cancelToken);

                await IOUtility.WriteAllBytes(temp, workspace.FileSystem.File, bytes);

                return(temp);
            }
        }
예제 #23
0
        protected void ProcessFiles(CommandLineApplication app, bool encrypt)
        {
            ValidateOptions();

            if (!string.IsNullOrEmpty(OutputDirectory) && !Directory.Exists(OutputDirectory))
            {
                Log.Info($"Creating directory : {OutputDirectory}.");
                Directory.CreateDirectory(OutputDirectory);
            }

            Log.Info("Listing files...");

            var filesList = GetFilesList(app).ToList();

            Log.Info($"Processing {filesList.Count} files.");

            var xcode = new UoeEncryptor(EncryptionKey);

            var i          = 0;
            var outputList = new List <string>();

            foreach (var file in filesList)
            {
                CancelToken?.ThrowIfCancellationRequested();
                var outputFile = Path.Combine((string.IsNullOrEmpty(OutputDirectory) ? Path.GetDirectoryName(file) : OutputDirectory) ?? "", $"{Path.GetFileName(file)}{(string.IsNullOrEmpty(OutputFileSuffix) ? "" : OutputFileSuffix)}");
                try {
                    xcode.ConvertFile(file, encrypt, outputFile);
                    outputList.Add($"{file} >> {outputFile}");
                } catch (UoeAlreadyConvertedException) { }
                i++;
                Log.ReportProgress(filesList.Count, i, $"Converting file to : {outputFile}.");
            }

            foreach (var file in outputList)
            {
                Out.WriteResultOnNewLine(file);
            }

            Log.Info($"A total of {outputList.Count} files were converted.");
        }
예제 #24
0
        public void Update()
        {
            if (mIsDisabledOnce)
            {
                mIsDisabledOnce = false;
                return;
            }

            WorkspaceInfo currentWkInfo = null;
            CancelToken   cancelToken   = new CancelToken();

            lock (mLock)
            {
                currentWkInfo = mWkInfo;

                if (currentWkInfo == null)
                {
                    return;
                }

                mCurrentCancelToken.Cancel();
                mCurrentCancelToken = cancelToken;
            }

            try
            {
                CheckIncomingChanges.ForWorkspace(
                    currentWkInfo, cancelToken,
                    mUpdateIncomingChanges);
            }
            catch (Exception ex)
            {
                mLog.ErrorFormat(
                    "Error checking new incoming changes from main for workspace '{0}': {1} ",
                    currentWkInfo.Name, ex.Message);
                mLog.DebugFormat(
                    "Stack trace:{0}{1}",
                    Environment.NewLine, ex.StackTrace);
            }
        }
            public async Task Do()
            {
                profile    = profileManager.Profiles.First(x => x.DisplayName == Settings.ProfileDisplayName);
                scanParams = new ScanParams
                {
                    DetectPatchCodes = Settings.OutputType == BatchOutputType.MultipleFiles && Settings.SaveSeparator == SaveSeparator.PatchT,
                    NoUi             = true,
                    DoOcr            = Settings.OutputType == BatchOutputType.Load ? (bool?)null // Use the default behaviour if we don't know what will be done with the images
                        : GetSavePathExtension().ToLower() == ".pdf" && ocrManager.DefaultParams?.LanguageCode != null,
                    OcrCancelToken = CancelToken
                };

                try
                {
                    CancelToken.ThrowIfCancellationRequested();
                    await Input();
                }
                catch (OperationCanceledException)
                {
                    return;
                }
                catch (Exception)
                {
                    CancelToken.ThrowIfCancellationRequested();
                    // Save at least some data so it isn't lost
                    await Output();

                    throw;
                }

                try
                {
                    CancelToken.ThrowIfCancellationRequested();
                    await Output();
                }
                catch (OperationCanceledException)
                {
                }
            }
예제 #26
0
        public async Task ImportAllFiles(IDictionary <string, string> dict, CancelToken cancelToken = null)
        {
            const string sql = @"
                SELECT f.hash, f.file_name
                FROM files f
                         JOIN folders_files ff ON f.id = ff.file_id;
            ";

            SQLiteConnection connection = await GetConnection(Path);

            try
            {
                if (cancelToken?.IsCanceled == true)
                {
                    return;
                }

                using (DbDataReader reader = await connection.ExecuteReaderAsync(sql))
                {
                    if (cancelToken?.IsCanceled == true)
                    {
                        return;
                    }

                    int hashIndex     = reader.GetOrdinal("hash");
                    int fileNameIndex = reader.GetOrdinal("file_name");

                    while (await reader.ReadAsync() && cancelToken?.IsCanceled != true)
                    {
                        dict[reader.GetString(hashIndex)] = reader.GetString(fileNameIndex);
                    }
                }
            }
            finally
            {
                ReleaseConnection();
            }
        }
예제 #27
0
        static void Main(string[] args)
        {
            try
            {
                AppInitializer.Initialize();

                var fileName         = args[0];
                var folder           = args[1]; //转换的图片存放的目录
                var progressFileName = args[2]; //记录进度的文件

                DTObject gt = DTObject.Create();

                using (var doc = DocumentFactory.Create(fileName))
                {
                    if (doc != null)
                    {
                        var token = new CancelToken();
                        var range = GetRange(folder, doc);
                        doc.ExtractImages(range.Index, range.Count, (pageIndex, content, g) =>
                        {
                            SavePage(folder, pageIndex, content, token, g);
                            RaiseCallback(progressFileName, g, gt);  //更新进度
                        }, token);

                        RaiseCallback(progressFileName, new Progress(doc.PageCount, doc.PageCount), gt);
                    }
                }
            }
            catch (Exception ex)
            {
                var errorFileName = args[3];  //记录错误的文件
                WriteError(errorFileName, ex);
            }
            finally
            {
                AppInitializer.Cleanup();
            }
        }
예제 #28
0
        private async Task ProcessSocketData()
        {
            IsRunning = true;

            // Buffers for received data
            var receivedMessage = new List <byte>();
            var buffer          = new byte[4096];

            while (true)
            {
                try
                {
                    // Get data until the complete message is received
                    WebSocketReceiveResult response;
                    do
                    {
                        response = await _client.ReceiveAsync(new ArraySegment <byte>(buffer), CancelToken);

                        receivedMessage.AddRange(new ArraySegment <byte>(buffer, 0, response.Count));
                    } while (!response.EndOfMessage);

                    // Decode the message
                    var messageJson = (new ASCIIEncoding()).GetString(buffer).Substring(0, receivedMessage.Count);
                    var data        = JsonConvert.DeserializeObject <TResponse>(messageJson);
                    receivedMessage.Clear();

                    // Notify subscriber
                    OnData(data);
                }
                catch (OperationCanceledException) { }

                if (CancelToken.IsCancellationRequested)
                {
                    IsRunning = false;
                    CancelToken.ThrowIfCancellationRequested();
                }
            }
        }
예제 #29
0
        public bool Is(out LinkedListNode <Token>[] argNodes, int argCount, Func <LinkedListNode <Token>, LinkedListNode <Token> > argGetNode, Func <Token, bool> argCond)
        {
            var pNodes = new LinkedListNode <Token> [argCount];
            var pNode  = NodeAct;

            for (var i = 0; i < argCount; i++)
            {
                CancelToken.ThrowIfCancellationRequested();

                if (pNode == null || !argCond.Invoke(pNode.Value))
                {
                    argNodes = null;

                    return(false);
                }
                pNodes[i] = pNode;
                pNode     = argGetNode(pNode);
            }

            argNodes = pNodes;

            return(true);
        }
예제 #30
0
        public void CancelRequest()
        {
            try
            {
#if DOT_NET
                // kill the task - we've timed out
                IsCancelled = true;
                if (WebRequest != null)
                {
                    CancelToken.Cancel();
                }
#else
                /* disposing of the www class causes unity editor to lock up
                 * if (WebRequest != null)
                 * {
                 *  WebRequest.Dispose();
                 * }*/
#endif
            }
            catch (Exception)
            {
            }
        }
예제 #31
0
        public void OnTick()
        {
            if (location == null)
            {
                FindClosestOre();
                return;
            }

            var token = new CancelToken();
            var map   = actions.AsyncMoveToLocation(location, token, MO);

            map.Completed += areaMap => {
                TaskCompleted();
            };
            map.Cancelled += (areaMap, cuboid) => {
                if (!token.stopped)
                {
                    token.Stop();
                    InvalidateBlock(location);
                    TaskCompleted();
                }
            };

            if (!map.Start())
            {
                if (!token.stopped)
                {
                    token.Stop();
                    InvalidateBlock(location);
                    TaskCompleted();
                }
            }
            else
            {
                busy = true;
            }
        }