0

When I'm debugging code everything is OK, and I don't get any errors, but without debugging I'm getting object reference not set to an instance of an object.

public async Task Execute(int id)
{
    var items = repository.GetItems(id);
    while(condition)
    {
        try
        {
            foreach (var item in items)
            {
                DoSomeWork(item);
            }
        }
        catch (Exception ex) { }
    }      
    await Task.Delay(1000);
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
I.pattern
  • 75
  • 1
  • 8
  • 1
    you are not awaiting anything in your code. – adt Mar 24 '20 at 09:24
  • this is not whole function, this is important part.. In the end I do await. Error is thrown in try block – I.pattern Mar 24 '20 at 09:26
  • No, it does not – I.pattern Mar 24 '20 at 09:30
  • Can't tell unless post your await part. – Louis Go Mar 24 '20 at 09:35
  • Now I added await part – I.pattern Mar 24 '20 at 09:40
  • 1
    Three options: a) GetItems returns null, b) the items list contains a null item (DoSomeWork throws), c) That's not the complete code in the try block. Summary: NullReferenceException have nothing to do with async. – jgauffin Mar 24 '20 at 09:44
  • Every item has value also GetItems does not return null. DoSomeWork throws NullReference, but when I'm debugging it, it works correctly and I'm not getting any errors – I.pattern Mar 24 '20 at 09:48
  • 1
    Doesn't the exception contain a stack trace you can use to pinpoint the location of the problem? – Lasse V. Karlsen Mar 24 '20 at 10:00
  • Since the `DoSomeWork` throws the `NullReferenceException`, you should debug that method, not the `Execute`. – Theodor Zoulias Mar 24 '20 at 10:42
  • The method works fine as I said. I debug and everything works, but when I skip debugging it throws error – I.pattern Mar 24 '20 at 10:45
  • Well then, something is happening differently when your program is running without the debugger attached. We can't tell what this thing is by looking the code in the question. I suggest that you embed in your program a [logging framework](https://stackoverflow.com/questions/1260157/whats-the-most-widely-used-logging-framework-in-c) so that you can log its behavior even when it's running on its own. – Theodor Zoulias Mar 24 '20 at 17:13

0 Answers0