I have a Dispatcher that I must use to update my bitmap, however the return line is executed before the code inside dispatcher finishes, so the result isn’t as expected.
How can I return a value after the dispatcher has completed? I can’t leave the return inside dispatcher.
Below is my code:
public ObservableCollection<FavoriteStruct> LoadMobion()
{
List<FavoriteMobion> results;
using (FavoriteDataContext context = new FavoriteDataContext(connectionString))
{
IQueryable<FavoriteMobion> query = from c in context.TbFavoriteMobion
select c;
results = query.ToList();
}
ObservableCollection<FavoriteStruct> lstFavStr = new ObservableCollection<FavoriteStruct>();
if (results != null)
{
Thread load = new Thread(new ThreadStart(() =>
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
foreach (var rst in results)
{
BitmapImage bi;
bi = new BitmapImage();
bi.UriSource = new Uri("../Images/default_avatar_small.jpg", UriKind.Relative);
lstFavStr.Add(new FavoriteStruct()
{
Opacity = 0.8f,
Status = "../Images/offline.png",
RealID = rst.RealID,
GroupType = rst.GroupType,
MsgStatus = rst.MsgStatus == "" ? "offline" : rst.Path,
Name = rst.Name,
Path = rst.Path == "" ? "" : rst.Path,
Phone = rst.Phone,
Picture = bi
});
}
});
}));
load.Start();
load.Join();
}
return lstFavStr;
}
You are calling a new thread and BeginInvoke is also done asynchronously, you can’t prevent return statement from executing when you want if you use threads. You should consider reformatting your code structure. I suggest you separate your UI update code, with the code you populate the collection. Take out populating the collection out of the thread.
Is your method supposed to load and display the data, or only return it? I would stop after getting the
result, return that, and use another method or code block to update the UI with that data. Simply separate the two tasks.