cap7
cap7

Reputation: 522

Make method run async and thread safe

I have this method in my ViewModel that querys items from the database:

public void GetProducts(DateTime date1, ...)
{
    var list = SQLQuery.GetProducts(DateTime date1, ...);

    Products = list.ToList();
}

On the view I call the method like this:

await Task.Run(() => vm.GetProducts(...));

That was the easy way I've found in order to make the UI responsive while the method is running. The problem is that I can't run the method a second time.

The compiler says that collection view that will be fed by that method is no longer thread safe.

So far I've trying to use the Dispatcher in order to run the method but I've not found a away to run it async and keep the await operator.

Upvotes: 0

Views: 334

Answers (1)

Charles Mager
Charles Mager

Reputation: 26223

You should separate the two - get the products on the background thread, then update the UI on the UI thread:

public IEnumerable<Product> GetProducts(DateTime date1, ...)
{
    return SQLQuery.GetProducts(DateTime date1, ...).ToList();    
}

And call like:

var products = await Task.Run(() => vm.GetProducts(...));
vm.Products = products;

Though I'd suggest this logic is moved into the view model as a command or similar.

Upvotes: 3

Related Questions