I am a relative noop at C# and his is my first attempt at asynchronous methods. I've put together a simple practice app (WPF MVVM) that lists the performance counters on my system. I've spent a few hours at this point reading questions and posts found via google. According to several of them, I am doing this wrong, but I made several attempts at making the below code work better. Admittedly, I am a bit confused by a lot of the documentation and help guides, on distinguishing between async and Tasks. This guide has offered a bit of help but I'm struggling to apply it to my code.
The Code
public async void UpdateCounters(PerformanceCounterCategory category) { await Task.Run(() => { Counters = GetCounters(category); }); } private ObservableCollection<PerformanceCounter> GetCounters(PerformanceCounterCategory category) { var countersList = new ObservableCollection<PerformanceCounter>(); if(category != null) { var instances = category.GetInstanceNames().OrderBy(ins => ins); if(instances.Any()) { foreach(var instance in instances) { if(category.InstanceExists(instance)) { //this is time consuming segment when I'm listing something like "Process" counters var counters = category.GetCounters(instance); foreach(var counter in counters) countersList.Add(counter); } } } } return countersList; } I've tried converting the method to an async method. Like so...
private async Task<List<PerformanceCounter>> GetCounters(PerformanceCounterCategory category) { //Changes receiving expression to Counter = new ObservableCollection(GetCounters(category)); var countersList = new List<PerformanceCounter>(); //But I couldn't figure out where to put the await I'm ultimately wanting to display "waiting..." or some other prompt/progress indicator on the UI, but I want to do it the right way. My current codes prevents it from being non-responsive, but that's about all.
Should this all be in a single async method, possibly like I've already done with a bit better coding, or should I be creating a list of tasks in the foreach. (I took at shot that too but it was an epic failure).
Design-Patternthat @PranayRana has used it will help you later in case you run across different patterns in Code / Design .NET Design Patterns