In my razor.cs file I have following async Task that is consuming data from Kafka topic in an endless while loop. When consuming is started the User Interface is blocked and the user cannot leave page or do other actions. How can I prevent this? I want to keep the while loop. Normaly I would like to close the connection with Dispose, when user leaves the page
my razor.cs code:
protected override void OnInitialized()
{
Read_Status_from_Kafka();
}
public async Task Read_Status_from_Kafka()
{
// code for configuring Kafka connection
while (true)
{
//consuming data form Kafka topic
}
}
As you have discovered, a thread [in this case the synchronisation context] can only do one thing at a time. You're expectation was that you can put it in a monitor loop and respond to UI events at the same time.
If you want to read the data all the time then a background task is a good solution.
If you only want to read the data when the page is active you can use a timer to do this. This "offloads" the operation of your while loop to the timer which is already running such a loop on a dedicated thread to handle all the registered timers.
Here's a demo page that sets up a timer on a page to run every second and update the UI if something changes.