简体   繁体   中英

How can I fix “exception has been thrown by the target of an invocation” while accessing data?

On the selection changed event I am accessing the data from one of my tables. But the "Exception has been thrown by the target of an invocation" is thrown.

var query = conn.Table<auto_fares>().Where(x => x.city == cbCity.SelectedItem);
var result = await query.ToListAsync();
foreach (var item in result)
{
    txtDistance.Text = item.min_km.ToString();
    lblDayFare.Text = item.min_fare.ToString();
    lblNightFare.Text = item.night_charges.ToString();
}

After adding the Dispose statement i am getting the following error as "The await operator can only be used within an async lamhda expression. Consider making this lamhda expression with the 'async' modifier."

How can I solve this?

Try re-writing your code like this:

var selectedCity = cbCity.SelectedItem;
var query = conn.Table<auto_fares>().Where(x => x.city == selectedCity);
var result = await query.ToListAsync();
foreach (var item in result)
{
    txtDistance.Text = item.min_km.ToString();
    lblDayFare.Text = item.min_fare.ToString();
    lblNightFare.Text = item.night_charges.ToString();
}

You're trying to access a UI component (cbCity.SelectedItem) from a non-UI thread (await query.ToListAsync() )

This foreach is executed asynchronously and you are accessing your UI from a different thread. Wrap your foreach in a Dispatcher.Invoke().

Like so:

Dispatcher.CurrentDispatcher.Invoke( new Action( () => {... your foreach...}   );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM