Talal Yousif
Talal Yousif

Reputation: 1094

C# Weird execution sequence

Please help me understand this. I have this code:

if (Entries == null)
{
    ExecuteAsync(Report);                
}

if (Entries == null)
{
    RaisError("No entries!");
    return;
}

My problem is that the execution starts with the first if, finds it true, executes the code block and exits with Entries still equals null, and hence executes the second code block. These are ExecuteAsync and Report methods:

public async void ExecuteAsync(Action executeAction, Action callbackAction = null)
{
    try
    {
        await Task.Run(executeAction);

        if (callbackAction != null)
            await Task.Run(callbackAction);
    }
    catch (Exception exception)
    {
        ModernDialog.ShowMessage(exception.Message, "Error", MessageBoxButtonOk);
    }
}


private void Report()
{
    Entries = DataAccessLayer.BrandReport(SelectedBrand, SelectedModel, FromDate, ToDate).ToList();

    TotalAmount = Entries.Sum(a => a.Amount);
    TotalQuantity = Entries.Sum(q => q.Quantity);
}

Although I am calling .ToList, I still get null in Entries!!!!

Upvotes: 0

Views: 61

Answers (1)

user1726343
user1726343

Reputation:

Well, you're executing Report asynchronously, and then you're skipping ahead to the second if block without doing anything with the Task returned by ExecuteAsync. It stands to reason that it is possible for your second if to be hit before DataAccessLayer.Brand... has been evaluated and assigned to Entries.

If you want to wait for Report to finish before the second Entries == null is evaluated, either call it synchronously (i.e. without ExecuteAsync), or use the Wait method on the Task returned by ExecuteAsync.

Upvotes: 1

Related Questions