Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Something like this could work.</p> <pre><code> private Dictionary&lt;Guid, TaskTracker&gt; _taskMap = new Dictionary&lt;Guid, TaskTracker&gt;(); private void OnButton1Click(object sender, EventArgs eventArgs) { TaskTracker taskTracker = new TaskTracker(Guid.NewGuid(), OnDoWork); _taskMap.Add(taskTracker.Identity, taskTracker); taskTracker.Run(); } private void OnDoWork() { // Do some work } private void OnButton2Click(object sender, EventArgs eventArgs) { Guid identity = _taskMap.Count &gt; 0 ? _taskMap.First().Value.Identity : default(Guid); // find some way to get the desired task TaskTracker taskTracker; if (_taskMap.TryGetValue(identity, out taskTracker)) { taskTracker.TaskExiting += OnTaskExiting; taskTracker.Stop(); } } private void OnTaskExiting(object sender, EventArgs eventArgs) { TaskTracker taskTracker = (TaskTracker)sender; taskTracker.TaskExiting -= OnTaskExiting; _taskMap.Remove(taskTracker.Identity); // do what you want with the timings } </code></pre> <p>The class for task is this:</p> <pre><code>public class TaskTracker { private readonly Action OnDoWork; private Task _task; private bool _isRunning = true; public TaskTracker(Guid identity, Action onDoWork) { Identity = identity; OnDoWork = onDoWork; } public readonly Guid Identity; public readonly Stopwatch Stopwatch = new Stopwatch(); public event EventHandler TaskExiting; public void Run() { Task _task = Task.Factory.StartNew( () =&gt; { Stopwatch.Start(); try { while (_isRunning) { OnDoWork(); } if (TaskExiting != null) { TaskExiting(this, EventArgs.Empty); } } finally { Stopwatch.Stop(); } } ); } public void Stop() { _isRunning = false; // wait for task to exit? _task = null; } } </code></pre> <p>You will need to fill in the blanks, meaning tracking tasks and getting the target task when hitting button 2.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload