首页 > 解决方案 > 在异步线程中分配对象?

问题描述

我正在使用托管 C++ 和 C#。我对以下代码有疑问。

//In C++, Run on background thread (not UI Thread)
while(true)
{
    BitmapSource^ bitmapSource = CreateBitmap();
    bitmapSource->Freeze();
    CSWrapperFuntion(bitmapSource); //this is a function pointer to C#
}

//In C#, Interface Project
 void CSWrapperFuntion(Object param)
 {
    mainWindow.Dispatcher.BeginInvoke(new Action(delegate()
    {
        BitmapSource bitmap = (BitmapSource)param;
        if (bitmap != null)
        {
            //Use this bitmap to display on UI Control
        }
    }));
 }

当我在异步线程(UI线程)中赋值BitmapSource bitmap = (BitmapSource)param;时,使用这个位图对象有什么问题吗?

在 BeginInvoke 的主体中,可能 Object 参数超出范围,是 GC 销毁?

我对 C# 的这种情况一无所知,所以我无法猜测将来会出现任何问题。

有人可以告诉我这段代码中的潜在错误吗?

非常感谢!

标签: c#asynchronousmanaged-c++

解决方案


推荐阅读