如何将元素添加到另一个线程绑定到XAML的IVector

时间:2018-03-13 01:33:12

标签: c++ windows uwp windows-runtime uwp-xaml

我目前正致力于Windows 10版本10.0.16299.0的Visual Studio Community 2017下的Windows 10 UWP C ++项目。

以下过程:我的计算机上运行了一个TCP服务器,它在某些事件中向连接的客户端发送消息。我正在处理的项目现在有我的TCPClient,它接收消息并应在UI中显示值。

在MainPage构造函数中,我创建了一个std :: thread,它调用了我的" clientThread"功能。在这个函数中,我实例化了我的客户端类的对象。一旦我连接到服务器,我就创建了一个新的std :: thread,它执行无限循环。这个循环调用" processPacketType"函数,它只是调用一个开关,并询问收到的数据包是否是ChatMessage数据包。如果是,则检索该消息。

现在我的问题:MainPage类有一个来自我创建的类的私有AudioSessionViewModel对象,它返回一个IVector ^。现在我想用我收到的消息扩展Vector。使用我的" processPacketType"函数,我只想实例化我的AudioSession类的新对象并将其添加到向量(我从线程传递给线程作为参考)。但是,我收到以下错误消息:在SoundManager - Client中的0x778B08C2上引发异常。 exe:Microsoft C ++异常:Platform :: InvalidCastException ^表示存储位置0x0F15EC3C。 HRESULT:0x80004002不支持接口 WinRT信息:不支持接口

有趣的是:我的processPacketType函数是从我的无限循环中调用的。如果我将新创建的对象传递给循环外的向量,它就可以工作。但如果我自己在循环中执行此操作,则会出现错误消息。

这个问题很难解释,但我希望你能理解我的需要。

//MainPage.xaml.h
namespace SoundManager___Client {
    public ref class MainPage sealed {
    public:
        MainPage();

        property AudioSessionViewModel^ ViewModel {
            AudioSessionViewModel^ get() { return this->viewModel; };
        }

    private:
        AudioSessionViewModel^ viewModel;
    };
}

//MainPage.xaml.cpp
#include "pch.h"
#include "MainPage.xaml.h"

using namespace SoundManager___Client;

using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;

void createClient(AudioSessionViewModel^ audioSessionViewModel);

MainPage::MainPage() {
    InitializeComponent();

    this->viewModel = ref new AudioSessionViewModel();

    std::thread client(createClient, this->viewModel);
    client.detach();
}

void createClient(AudioSessionViewModel^ audioSessionViewModel) {
    Client myClient("127.0.0.1", 1111, audioSessionViewModel);
    myClient.Connect();

    std::string buffer;

    while (true) {
        Sleep(10000);
    }
}

namespace SoundManager___Client {
    bool Client::processPacketType(const PacketType _packetType, AudioSessionViewModel^ audioSessionViewModel) {
        switch (_packetType) {
        case PacketType::ChatMessage: {
            std::string message;
            if (!getString(message))
                return false;

            OutputDebugStringA((LPCSTR)message.c_str());
            OutputDebugString(L"\n");
            audioSessionViewModel->AudioSessions->Append(ref new AudioSession(L"Test", L"20")); //<--------- Here I get the error

            break;
        }
        default:
            OutputDebugString(L"Unrecognized PacketType.\n");
            break;
        }
        return true;
    }

    void Client::clientThread(Client &_client, AudioSessionViewModel^ audioSessionViewModel) {
        PacketType packetType;
        //If I put the code to add the element over here, it works. But it doesn't inside the while loop or in the processPacketType which get called inside the loop
        while (true) {
            if (_client.mTerminateThreads == true)
                break;

            if (!_client.getPacketType(packetType))
                break;

            if (!_client.processPacketType(packetType, audioSessionViewModel))
                break;
        }

        OutputDebugString(L"Lost connection to the server.\n");
        _client.mTerminateThreads = true;
        if (!_client.closeConnection())
            OutputDebugString(L"Socket to the server was closed successfully.\n");
        else
            OutputDebugString(L"Socket was not able to be closed.\n");
    }

#pragma once

#include <sstream>

namespace SoundManager___Client {
    public ref class AudioSession sealed {
    private:
        Platform::String^ sessionName;
        Platform::String^ sessionVolume;

    public:
        AudioSession(Platform::String^ sessionName, Platform::String^ sessionVolume) : sessionName{ sessionName }, sessionVolume{ sessionVolume } { }

        property Platform::String^ SessionName {
            Platform::String^ get() { return this->sessionName; }
        }
        property Platform::String^ SessionVolume {
            Platform::String^ get() { return this->sessionVolume; }
        }
        property Platform::String^ OneLineSummary {
            Platform::String^ get() {
                std::wstringstream wstringstream;
                wstringstream << this->SessionName->Data();
                wstringstream << this->SessionVolume->Data();
                return ref new Platform::String(wstringstream.str().c_str());
            }
        }
    };

    public ref class AudioSessionViewModel sealed {
    private:
        Windows::Foundation::Collections::IVector<AudioSession^>^ audioSessions;

    public:
        AudioSessionViewModel() {
            this->audioSessions = ref new Platform::Collections::Vector<AudioSession^>();

            AudioSession^ audioSession = ref new AudioSession(L"MASTER", L"100");
            this->audioSessions->Append(audioSession);
            audioSession = ref new AudioSession(L"CHROME", L"50");
            this->audioSessions->Append(audioSession);
        }

        property Windows::Foundation::Collections::IVector<AudioSession^>^ AudioSessions {
            Windows::Foundation::Collections::IVector<AudioSession^>^ get() { return this->audioSessions; }
        }
    };
}

解决方案 - 更新: 我终于想出了如何在C ++ / CX中调用调度程序:

Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(Windows::UI::Core::CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]() {

}));

现在我终于理解了为什么我的电话有效,但只是在循环之外:

我假设至少来自std :: thread的调用在UI线程中执行第一次执行,并且只有当它到达.detach()时,代码才会在新线程中执行。如果我错了,我会在评论中要求更正!

2 个答案:

答案 0 :(得分:1)

我认为问题在于您将后台线程中的项目添加到AudioSessions,同时将其绑定到xaml;要更改UI,您需要在UI线程中。使用Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync获取UI线程,然后将其添加到集合中

答案 1 :(得分:0)

使用解决方案和解释更新了主要帖子!