public TaskData(CancellationTokenSource cancellationTokenSource, AddressRange addressRange) { CancellationTokenSource = cancellationTokenSource; Result = new Result(addressRange); }
void AddScanTask(AddressRange addressRange) { var cancellationTokenSource = new CancellationTokenSource(); Task <List <ulong> > task = Task.Run(() => { try { return(MemoryHelper.FindPatternAddresses(Process, addressRange, Pattern, StopAfterFirst)); } catch (TaskCanceledException) { } catch (Exception ex) { Log.WriteException(ex); } return(null as List <ulong>); }, cancellationTokenSource.Token); task.ContinueWith((continuingTask) => { try { TaskData data = null; lock (m_Tasks) { m_Tasks.TryGetValue(continuingTask, out data); } if (data == null) { return; } data.Result.Complete(); if (HasCompleted) { return; } if (continuingTask.Result != null && continuingTask.Result.Any()) { Pattern.Addresses.AddRange(continuingTask.Result.Select(address => address)); data.Result.Matches.AddRange(continuingTask.Result); // Cancel all other threads and complete the scan because we needed only 1 result if (StopAfterFirst) { TryCancel(); } } // Complete the scan if this is the last thread to finish if (!HasCompleted) { int completedTaskCount = 0; lock (m_Tasks) { completedTaskCount = m_Tasks.Select(t => t.Key).Where(thisTask => thisTask.IsCompleted).Count(); } if (completedTaskCount == m_Tasks.Count) { TryComplete(); } } } catch (TaskCanceledException) { } catch (Exception ex) { Log.WriteException(ex); } }); lock (m_Tasks) { m_Tasks.TryAdd(task, new TaskData(cancellationTokenSource, addressRange)); } }