BTOM
BTOM

Reputation: 73

Blazor Server Periodic update of images using a timer

Sorry for the rudimentary question.

An image is pasted and displayed on a web page created with Blazor Server.

I would like to update this displayed image on a regular basis. (For example, updated every second)

This image is stored in the location wwwroot / imageFiles with the name PreviewImage.bmp.

Specifically, I want to switch the image displayed on the web page to the replaced image when PreviewImage.bmp under this wwwroot / imageFiles is replaced.

For example, when I change PreviewImage.bmp that shows a dog to PreviewImage.bmp that shows a cat, I want to switch the image displayed on the web page.

I wondered if I could update the image using StateHasChanged (); with a timer, but this didn't work.

<img src="@previewImg" />

@code{
    
    private string previewImg = string.Empty;
    private Timer timer = new(1000);

    protected override void OnInitialized()
    {
        previewImg = @"imageFiles/PreviewImage.bmp";

        timer.Elapsed += (sender, eventArgs) => OnTimerCallback();
        timer.AutoReset = true;
        timer.Start();            
    }

    private void OnTimerCallback()
    {    
        _ = InvokeAsync(() =>
       {    
         previewImg = @"imageFiles/PreviewImage.bmp";
         StateHasChanged();
       });
    }
 }

However, if you reload the entire page with the F5 key, the image will be updated.

Is there a way to achieve this image update?

I'm sorry that the content is very difficult to understand.

Thank you for your advice.

Upvotes: 0

Views: 1498

Answers (2)

klekmek
klekmek

Reputation: 563

Try this

protected override void OnInitialized()
{
    var timer = new System.Threading.Timer(_ =>
    {    
        InvokeAsync( async ()  =>
        {
            previewImg = @"imageFiles/PreviewImage.bmp";
            StateHasChanged();
        });
    }, null, 0, 1000);

}

Upvotes: -1

Bennyboy1973
Bennyboy1973

Reputation: 4208

Try putting a junk query after the file name, something like:

previewImg = @"imageFiles/PreviewImage.bmp" + "?DummyId=" + DateTimeNow.Ticks;

Upvotes: 5

Related Questions