-1

This is probably extremely easy but I'm just starting with async methods so I need help. I want to cache table into a List<> while WinForm loads just to save some time. I need to execute simple task as async :
List<item> itemsList = dataContext.Items.Where(x=>x.Active == true).ToList<Item>()
It is a single task, no need for CancellationTokenSource

ArtK
  • 1,157
  • 5
  • 17
  • 31
  • 3
    Looks like you want to use [`ToListAsync`](https://msdn.microsoft.com/en-us/library/dn220262(v=vs.113).aspx) – juharr Aug 01 '16 at 14:49
  • As juharr wrote: `List itemsList = await dataContext.Items.Where(x=>x.Active == true).ToListAsync();` Also possible duplicate [How can I use async to increase WinForms performance?](http://stackoverflow.com/q/14962969/1260204) – Igor Aug 01 '16 at 14:50
  • the point of async is to release the UI thread for long running processes that require external resources. This does not sound like a good use case for this. That said, your explanation is not clear. Cache how? – Liam Aug 01 '16 at 14:56
  • @Liam - you are correct - async methods offload I/O operations to a thread from ThreadPool and ensure release of the thread once Task is complete. When I contact remote database, I perform I/O operation. Caching in this case is loading table content from the database into client's memory. The purpose of this caching is to limit traffic and database workload when additional filtering is done to table's content. – ArtK Aug 30 '16 at 13:56

1 Answers1

1

You need a combination of ToListAsync as the comments suggested and an async OnLoad event handler like below. You won't be able to await in the constructor, and you have to mark your events async void to be able to await in them.

private List<Item> itemsList = null;

        public Form1()
        {
            InitializeComponent();
            Load += OnLoad;
        }

        private async void OnLoad(object sender, EventArgs eventArgs)
        {
            itemsList = await dataContext.Items.Where(x => x.Active == true).ToListAsync();
        }
rmc00
  • 877
  • 10
  • 20
  • My winforms is rusty, but isn't this just async over sync anti pattern? I.e. because Load is synchronous marking OnLoad as async has zero effect? – Liam Aug 01 '16 at 14:58