Category: async

Saving multiple data–part 31

I want to load the exchange rates from NBR and ECB and load at once .From here, the challenges of programming for a simple task like this:

  1. How we can display the errors ?
  2. What if the data exists already for this day and I cannot save into database, because it exists ?
  3. How to acknowledge what exists and what not , in one operation ?
  4. How to report success even if data exists ? Should we report number of records?
  5.  How we can perform async all that stuff and, however , report errors ?

If you know the answer to all that, I have a challenge for you: see the file at https://github.com/ignatandrei/InfoValutar/blob/master/InfoValutar/InfovalutarLoadAndSave/LoadAndSaveLastData.cs– and improve it.

Until then, I come with this simple code

 

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class ResultsLoadBankData
    {
        public string Bank { get; internal set; }
        public int NrRecords { get; internal set; }
        public bool HasSuccess { get; internal set; }
        public string ErrorMessage { get; internal set; }
    }
 
//in some class below
public async Task<ResultsLoadBankData[]> LoadAndSave()
        {
             
             
            var items= providers.Banks().Select(it =>
                new KeyValuePair<string, ResultsLoadBankData>(it,
                new ResultsLoadBankData()
                {
                    Bank = it,
                    ErrorMessage=null,
                    HasSuccess=true,
                    NrRecords=0
                })
             );
            var lst = new Dictionary<string, ResultsLoadBankData>(items);
 
 
            var rates =
                providers.LoadExchange()
                .Select(it => it.GetActualRates())
                .ToArray();
            //TODO: how to load async all async enumerables?
            //TODO: how to report error if one fails?
            foreach (var rateAsync in rates)
            {
                 
                await foreach(var rate in rateAsync)
                {
                    var item = lst[rate.Bank];
                    try
                    {
                         
                        if (await ret.Exists(rate))
                            continue;
                        var nr = await save.Save(rate);
                        item.NrRecords++;
                    }
                    catch(Exception ex)
                    {
                        //TODO:log
                        item.ErrorMessage = ex.Message;
                        item.HasSuccess = false;
                    }
                }
                 
                 
            }
            return lst.Values.ToArray();
        }

Infovalutar

And one hour passes...
(This is the result of 1 hour per day auto-challenge as a full cycle developer for an exchange rates application)
( You can see the sources at https://github.com/ignatandrei/InfoValutar/ )

My Async Await tutorials

Rule of thumb: just await / async from top to down.

 

To deeply understand async await in .NET Core , please follow the following resources:

 

1. https://channel9.msdn.com/Events/TechDays/Techdays-2014-the-Netherlands/Async-programming-deep-dive  – to gain inner knowledge about what code is async / await

2. Read https://blog.stephencleary.com/2012/02/async-and-await.html to have started into async await

3. Read MSDN for a better understanding : https://msdn.microsoft.com/en-us/magazine/jj991977.aspx?f=255&MSPPError=-2147217396

4. Common pitfalls in ASP.NET  Framework( not in console! ) with async await: https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html

5. No problem in ASP.NET Core: https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

Happy reading !

Asynchronous code and exceptions

There are 2 kinds of coding when handling asynchronous code.

The first one is  calling Result:

<

The second is async /await

1
2
3
4
5
6
7
8
public async Task<bool> TwoTask() {
 
//code
 
await Task.WhenAll(file, console);
return file.Result & console.Result;
 
}

As such, we will have 2 intercepting code.

For the first one we will catch AggregateException

1
2
3
4
5
6
7
8
try
            {
                Console.WriteLine(t.TwoTask().Result);
            }
            catch (AggregateException ex)
            {
                Console.WriteLine("Aggregate number of exceptions :"+ex.InnerExceptions.Count);
            }

For the second one we will catch the FIRST task  exception  ( or , more generic , Exception ) – and see what other tasks have been doing

try

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
try
            {
                await Task.WhenAll(file, console);
                return file.Result & console.Result;
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine("Exception is " + ex.Message);
                 
                if (file.IsFaulted)
                {
                    Console.WriteLine("file is faulted exceptions :" + file.Exception.InnerExceptions.Count);
                     
                }
                if (console.IsFaulted)
                {
                    Console.WriteLine("console is faulted exceptions :" + console.Exception.InnerExceptions.Count);
                }
                 
                throw;
            }

Maybe it is better when you see a video demo: Async await and exceptions at https://youtu.be/1a9s74IfSE8

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.