2
votes

Trying to get things working correctly in Blazor Server Side App. I have an Uploader Component but it doesn't InvokeAsync after each promise is resolved on client side. It waits for all Images to load then Invokes the C# method. How would I get it to Invoke the C# method after each image is loaded?

I know JavaScript is single threaded but also tried with web workers and still does the same thing.

Sample repo can be found here https://dev.azure.com/twinnaz/BlazorUploader

Gif of what's happening.

https://imgur.com/a/aF4AQUf

It should be able to invoke the C# method Async in parallel from javascript file if my thinking is correct.

2

2 Answers

3
votes

This issue is related with Blazor and JS. On JS you are not awaiting for GenerateImageData.

You should to use a modern for … ofloop instead, in which await will work as expected:

GetFileInputFiles = async (instance, fileInput) => {
    var files = Array.from(fileInput.files);
    for (const image of files) {
        var imagedata = await readUploadedFileAsText(image);
        console.log("sending");
        _ = await instance.invokeMethodAsync('GenerateImageData', imagedata);
        console.log("sent");
    };
};

On Blazor, I suggest to you to rewrite GenerateImageData as :

    [JSInvokable]
    public async Task GenerateImageData(string data)
    {
        System.Console.WriteLine( "Receiving"  );
        ImageBase64.Add(data);
        await Task.Delay(1);
        StateHasChanged();
        System.Console.WriteLine( "Received"  );
    }

Result:

enter image description here

0
votes
GeneratePreviewImages = async (dotNet, fileInput) => {

    const files = Array.from(fileInput.files);

    const imageSrcs = files.map(file => getPreviewImageSrc(file));
    loop(imageSrcs, dotNet);
};



const loop = async (arr, dotNet) => {
    for await (const src of arr) {
        console.log(src);
        dotNet.invokeMethodAsync('GenerateImageData', src);
    }
};

const getPreviewImageSrc = async (file) => {
  return  URL.createObjectURL(file);
};