C
C#2y ago
frknztrk

❔ C Task this.Dispatcher.Invoke lock problem

private void Page_Loaded(object sender, RoutedEventArgs e)
{
letspaly = Task.Run(() => loadItem());

letspaly.Wait();
Debug.WriteLine("End ?");
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
letspaly = Task.Run(() => loadItem());

letspaly.Wait();
Debug.WriteLine("End ?");
}
public void loadItem()
{
using (var entitydb = new AyetContext())
{

this.Dispatcher.Invoke(() =>
{
listBorder.Visibility = Visibility.Visible;
stackBorder.Visibility = Visibility.Collapsed;
});

}

}
public void loadItem()
{
using (var entitydb = new AyetContext())
{

this.Dispatcher.Invoke(() =>
{
listBorder.Visibility = Visibility.Visible;
stackBorder.Visibility = Visibility.Collapsed;
});

}

}
I will get the data every time the page is loaded with the task, but the program hangs with invoke while the task is waiting
5 Replies
canton7
canton72y ago
Yep, classic async dealock. Your UI thread is blocked on the Wait, so that Dispatcher.Invoke is never going to get executed (the UI thread can't run it as it's blocked on the Wait), and that means that the letspaly Task never completes, so the Wait never completes, so the UI thread is never freed
mrphil2105
mrphil21052y ago
Also it doesn't seem like the code in the Task.Run does much in terms of CPU work. Don't use Task.Run for this IO is even more reason to not use Task.Run If there are async overloads for I/O that is Task.Run in that case is completely pointless But the anwser is that you are using Wait() in a UI context/thread. This will in many cases result in a deadlock. Tip: NEVER EVER use Wait() Always await But that can be done with DbContext's async methods Task.Run is useless here But is saying don't use Task.Run an issue? Use the async methods and not Task.Run As to why - that's a longer topic indeed
frknztrk
frknztrk2y ago
this.Dispatcher.InvokeAsycn(()); I solved the problem by doing this
mrphil2105
mrphil21052y ago
But still don't use Wait There are no good usages of Wait ever In very rare cases GetAwaiter().GetResult() can be used. But that's like 0.1% of the time No, use await
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.