简体   繁体   English

Task.Run 在执行完成后不会让线程死亡

[英]Task.Run doesn't let thread die after execution finishes

I am working on C# code which calls C++ code for sending data to the server.我正在研究C#代码,该代码调用C++代码以将数据发送到服务器。

I used Task.Run() for the thread.我使用Task.Run()作为线程。

Once the function returns the thread should die, but the problem is it doesn't and creates a new thread whenever there is data.一旦 function 返回线程应该死掉,但问题是它不会,只要有数据就会创建一个新线程。

Here is the code where I call the Task.Run这是我调用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.我附上了屏幕截图,您可以在其中看到创建了太多线程。

截屏

I solved it with this link where created a buffer and fill it with frame.我用这个链接解决了这个问题,该链接创建了一个缓冲区并用框架填充它。 The main issue I have to dispose softwareBitmap objects.我必须处理 softwareBitmap 对象的主要问题。 Here is the link Solution这是链接解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM