Home > Enterprise >  Task.Run doesn't let thread die after execution finishes
Task.Run doesn't let thread die after execution finishes

Time:08-17

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

CodePudding user response:

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

  • Related