无效的跨线程访问问题

2024-05-08

我有两个 ViewModel 类:PersonViewModel 和 PersonSearchListViewModel。 PersonViewModel 实现的字段之一是通过 WCF 下载的个人资料图像(本地缓存在独立存储中)。 PersonSearchListViewModel 是一个包含人员列表的容器类。由于加载图像相对繁重,PersonSearchListViewModel 仅加载当前页面、下一页和上一页的图像(结果在 UI 上分页)...为了进一步改善图像的加载,我将图像的加载放在另一个线程上。然而,多线程方法会导致跨线程访问问题。

人视图模型:

public void RetrieveProfileImage()
{
    Image profileImage = MemorialDataModel.GetImagePerPerson(Person);
    if (profileImage != null)
    {
        MemorialDataModel.ImageManager imgManager = new MemorialDataModel.ImageManager();
        imgManager.GetBitmap(profileImage, LoadProfileBitmap);
    }
}

private void LoadProfileBitmap(BitmapImage bi)
{
    ProfileImage = bi;
    // update 
    IsProfileImageLoaded = true;
}

private BitmapImage profileImage;
public BitmapImage ProfileImage
{
    get
    {
        return profileImage;
    }
    set
    {
        profileImage = value;
        RaisePropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("ProfileImage"));
    }
}

人员搜索列表视图模型:

private void LoadImages()
{
    // load new images 
    Thread loadImagesThread = new Thread(new ThreadStart(LoadImagesProcess));
    loadImagesThread.Start();

    //LoadImagesProcess(); If executed on the same thread everything works fine 
}

private void LoadImagesProcess()
{
    int skipRecords = (PageIndex * PageSize);
    int returnRecords;

    if (skipRecords != 0)
    {
        returnRecords = 3 * PageSize; // page before, cur page and next page 
    }
    else
    {
        returnRecords = 2 * PageSize;   // cur page and next page 
    }

    var persons = this.persons.Skip(skipRecords).Take(returnRecords);

    // load images 
    foreach (PersonViewModel pvm in persons)
    {
        if (!pvm.IsProfileImageLoaded)
        {
            pvm.RetrieveProfileImage();
        }
    }
}

如何以多线程方式处理ViewModel类中的数据?我知道你必须在 UI 上使用调度程序来更新。如何更新绑定到 UI 的 ViewModel ?

** 编辑 **

还有一个更奇怪的错误发生。在下面的代码中:

        public void GetBitmap(int imageID, Action<BitmapImage> callback)
        {
            // Get from server 
            bitmapCallback = callback;

            memorialFileServiceClient.GetImageCompleted += new EventHandler<GetImageCompletedEventArgs>(OnGetBitmapHandler);
            memorialFileServiceClient.GetImageAsync(imageID);
        }

        public void OnGetBitmapHandler(object sender, GetImageCompletedEventArgs imageArgs)
        {
            if (!imageArgs.Cancelled)
            {
                // I get cross-thread error right here 
                System.Windows.Media.Imaging.BitmapImage bi = new BitmapImage();
                ConvertToBitmapFromBuffer(bi, imageArgs.Result.Image);

                // call call back
                bitmapCallback.Invoke(bi);
            }
        }

尝试在后台线程中创建新的 BitmapImage 对象时出现跨线程错误。为什么我不能在后台线程上创建新的 BitmapImage 对象?


为了更新 ViewModel 中的 DependencyProperty,请使用与访问任何其他 UIElement 相同的调度程序:

System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => {...});

此外,BitmapImages 必须在 UI 线程上实例化。这是因为它使用了 DependencyProperties,该属性只能在 UI 线程上使用。我尝试在单独的线程上实例化 BitmapImages,但它不起作用。您可以尝试使用其他方法将图像存储在内存中。例如,当您下载图像时,将其存储在 MemoryStream 中。然后 UI 线程上的 BitmapImage 可以将其源设置为 MemoryStream。

您可以尝试在 UI 线程上实例化 BitmapImages,然后在另一个线程上使用 BitmapImage 执行其他所有操作...但这会变得很麻烦,我什至不确定它是否会起作用。以下是一个例子:

System.Windows.Media.Imaging.BitmapImage bi = null;
using(AutoResetEvent are = new AutoResetEvent(false))
{
    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
    {
        bi = new BitmapImage();
        are.Set();
    });
    are.WaitOne();
}

ConvertToBitmapFromBuffer(bi, imageArgs.Result.Image);
bitmapCallback.Invoke(bi);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无效的跨线程访问问题 的相关文章

随机推荐