-2

I am working on C# code which calls C++ code for sending data to the server.

I used Task.Run() for the thread.

Once the function returns the thread should die, but the problem is it doesn't and creates a new thread whenever there is data.

Here is the code where I call the Task.Run

private void ColorFrameReader_FrameArrivedAsync(MediaFrameReader sender, MediaFrameArrivedEventArgs args)
{
    var frame = sender.TryAcquireLatestFrame();
    if (frame != null)
    {
        SoftwareBitmap originalBitmap = null;
        var inputBitmap = frame.VideoMediaFrame?.SoftwareBitmap;
        if (inputBitmap != null)
        {
            // The XAML Image control can only display images in BRGA8 format with premultiplied or no alpha
            // The frame reader as configured in this sample gives BGRA8 with straight alpha, so need to convert it
            originalBitmap = SoftwareBitmap.Convert(inputBitmap, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);                 
            SoftwareBitmap outputBitmap = new SoftwareBitmap(BitmapPixelFormat.Bgra8, originalBitmap.PixelWidth, originalBitmap.PixelHeight, BitmapAlphaMode.Premultiplied);

            //this thread goes to the c++ code and start the TCP communication                
            //var task = Task.Factory.StartNew(() => { ct.ThrowIfCancellationRequested(); _helper.Connect(originalBitmap); }, cts.Token);
            //_helper is the objet of C++ class where it connect and send the frames to the server and Connect is the method where it send.
            Task.Run(() => { _helper.Connect(originalBitmap); });
        }
    }
    
}

I am attaching the screenshot, where you can see that too many threads are created.

screenshot

Rand Random
  • 7,300
  • 10
  • 40
  • 88
Nifty
  • 67
  • 8
  • 4
    Could you please add your Task.Run code so that developers can see and make a comment ? – ahmet gül Aug 09 '22 at 13:49
  • 3
    [Task.Run](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run) does not create or destroy threads, but schedules your code to run on the thread pool. When your code finished (or blocks), the thread is handed back to the thread pool. Creating and desstroyal of threads is up to what the thread pool thinks is useful. – Klaus Gütter Aug 09 '22 at 13:58
  • did you try to dispose the bitmaps you are using? – Rand Random Aug 09 '22 at 14:09
  • No @RandRandom could you guide me to some site for that? Thank you for your text clean and reply! – Nifty Aug 09 '22 at 14:13
  • have a look at: https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged | https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose | https://learn.microsoft.com/en-us/dotnet/api/system.idisposable?view=net-6.0 – Rand Random Aug 09 '22 at 14:15
  • after `_helper.Connect(originalBitmap);` call `originalBitmap.Dispose();` don't understand the meaning of `outputBitmap` since it never gets used, but it should be disposed aswell, since I fail to understand its usage, I can't tell where it would be safe to dispose it (either inside the Task.Run or outside of it) – Rand Random Aug 09 '22 at 14:16
  • But if Task.Run() schedule the task then If I dispose it then did'nt it lost the frame data in originalBitmap? – Nifty Aug 09 '22 at 14:21
  • I did try that but it is not able to send the frame to the server now, only first frame it get then it simple not responding. – Nifty Aug 09 '22 at 14:22
  • did you put the dispose at the right place? `Task.Run(() => { _helper.Connect(originalBitmap); originalBitmap.Dispose(); });` inside the `Task.Run`? (please answer to comments with @username) – Rand Random Aug 09 '22 at 15:01
  • @RandRandom it gives Exception: Exception thrown at 0x6BA6282C (OpenCVBridge.dll) in CameraOpenCV.exe: 0xC0000005: Access violation reading location 0x00000000. In this function bool OpenCVHelper::GetPointerToPixelData(SoftwareBitmap^ bitmap, unsigned char** pPixelData, unsigned int* capacity) – Nifty Aug 09 '22 at 15:35
  • Maybe this is helpful https://stackoverflow.com/questions/49250691/how-to-properly-release-bitmapbuffer-from-softwarebitmap-uwp but not really something I am familiar with – Rand Random Aug 09 '22 at 15:38
  • 1
    @RandRandom your comment help a lot to me Thank you!. This solve my problem https://learn.microsoft.com/en-us/windows/uwp/audio-video-camera/process-media-frames-with-mediaframereader?fbclid=IwAR1ytn14wHQY1Aj4t7OSsgvsogqW_nvjOCQkX8FHq2sMREsouciexHfTYus – Nifty Aug 09 '22 at 16:19
  • Your `Task.Run` code is an example of what is known as fire-and-forget, which is frowned upon by the experts. You could take a look on [this recent answer](https://stackoverflow.com/questions/73288575/calling-an-asynchronous-method-without-await-recommended/73294628#73294628) to see what Stephen Cleary has to say about fire-and-forget. – Theodor Zoulias Aug 09 '22 at 17:43
  • 1
    @TheodorZoulias thanks for the reply, yeah now i am using async/await – Nifty Aug 10 '22 at 08:14

1 Answers1

1

I solved it with this link where created a buffer and fill it with frame. The main issue I have to dispose softwareBitmap objects. Here is the link Solution

Nifty
  • 67
  • 8
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 12 '22 at 21:20