0

I have two solution:

Sol1:

 public class Sol1{

  internal override IList<MenuItem> MenuItems
  {
   //some code
   GetItems();

   return items;
  }

  internal override async void GetItems()
  {
    //code
    //async method
    //code
    //async method
  }
 }

Solution one is creating first first level of menu. Then into Solution 2, after fist level menu is created I want to have access to this "items".

Sol2:

public class Sol2{

  private async Task SecondLev{
     //some code
   Sol1 sol1 = new Sol1();
   var test = sol1.items;
  }
}

But they are always empty. I don't want to run one more time method MenuItems, but have access to this items.

4est
  • 3,010
  • 6
  • 41
  • 63
  • https://stackoverflow.com/questions/9343594/how-to-call-asynchronous-method-from-synchronous-method-in-c –  Jan 17 '20 at 11:25
  • Also you're not calling either `MenuItems` or `GetItems` in your `SecondLev` method. –  Jan 17 '20 at 11:27
  • And it seems like you want to switch from async (`SecondLev`) to non-async (`MenuItems`) to async (`GetItems`), this feels like a bad practice. –  Jan 17 '20 at 11:29

1 Answers1

4

They are empty, because you don't await async operation.

Your code should look like:

    public class Sol1
    {
        internal IList<MenuItem> MenuItems { get; private set; }

        internal async Task GetItems()
        {
            // some async code
            // ...
            MenuItems = someResult;
        }
    }

    public class Sol2
    {
        private async Task SecondLevel()
        {
            //some code
            Sol1 sol1 = new Sol1();
            await sol1.GetItems();
            var test = sol1.MenuItems;
        }
    }

Few notes:

  1. Don't make async void methods if they are not an event handlers, use async Task instead.
  2. You cannot have async properties, only async methods.
Alexander Goldabin
  • 1,824
  • 15
  • 17