簡體   English   中英

異步等待操作阻止UI從另一個Frame返回時

[英]Async Await operation blocking UI on return from another Frame

我是C#和UWP的新手,這是一項任務,我的交稿時間很緊,所以還沒有時間完全弄清楚問題,因此請原諒。

我有以下代碼,該代碼通過創建AMQP連接並以恆定的while循環從Azure IOT集線器接收消息來工作。

有適當的問題分配,但主要的問題是當我從訪問另一頁面返回時,GUI停止更新文本字段。

實際上,它確實從OnNavigatedTo更新了它們,但是方法Receive Messages停止更新它們,但是在輸出窗口中,我可以看到debug.write正在接收消息,只是不更新​​文本字段。

我想我需要在單獨的線程上運行while循環,但我認為下面沒有做過,我已經讀過Task.Run等,並嘗試了各種方法,但無法弄清楚。

    public MainPage()
    {
        this.InitializeComponent();
        if (receivedStarted != 1)
            Receive();
    }

    private async void Receive()
    {
        await ReceiveMessages("1");
        await ReceiveMessages("0");
    }

    /// <summary>
    /// On Navigated to function from other pages
    /// </summary>
    /// <param name="e"></param>
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        Counter.Text = parsedCounter;
        TimeText.Text = "The last activity was at " + parsedTime;
        Contact_1.Content = ContactAddPopUp.contact[0, 0];
        Contact_2.Content = ContactAddPopUp.contact[1, 0];
        Contact_3.Content = ContactAddPopUp.contact[2, 0];

        if (Settings.timeChanged == true)
        {
            if (DelayTimer != null)
            {
                DelayTimer.Cancel();
                Timer();
            }
        }
    }
    /// <summary>
    /// Receive messages from specified azure iothub on specified partition. The MessageManager parses the received message and displays it accordingly
    /// </summary>
    /// <param name="partition"></param>
    /// <returns></returns>
    public async Task ReceiveMessages(string partition)
    {         
        DateTime offset;
        offset = DateTime.UtcNow - TimeSpan.FromMinutes(1);
        String primaryKey = "fghkfwhihelfihefjw;ojwef";
        String sharedAccessPolicy = "iothubowner";
        //String hubName = "RaspberryPirSensor";
        String deviceName = "PIRSensor";
        String eventHubEntity = "iothub-ehub-raspberryp-70680-20f0331ccb";

        string port = "iakugfdkjhkjhaflhlkhalkfhse.servicebus.windows.net";
        Address address = new Address(port, 5671, sharedAccessPolicy, primaryKey, "/", "amqps");
        Connection connection = await Connection.Factory.CreateAsync(address);
        Session session = new Session(connection);
        string totalMilliseconds = ((long)(offset - new DateTime(StartOfEpoch, DateTimeKind.Utc)).TotalMilliseconds).ToString();
        Map filters = new Map();
        filters.Add(new Amqp.Types.Symbol("apache.org:selector-filter:string"),
                                    new DescribedValue(
                                        new Amqp.Types.Symbol("apache.org:selector-filter:string"),
                                        "amqp.annotation.x-opt-enqueuedtimeutc > " + totalMilliseconds + ""));
        ReceiverLink receiver = new ReceiverLink(session,
            "my-receiver",
            new global::Amqp.Framing.Source()
            {
                Address =
            eventHubEntity + "/ConsumerGroups/$Default/Partitions/" + partition,
                FilterSet = filters
            }, null);

        Amqp.Types.Symbol deviceIdKey = new Amqp.Types.Symbol("iothub-connection-device-id");
        string deviceId = deviceName;
        while (true)
        {
            if (timerCreated == false)
                Timer();
            receivedStarted = 1;
            Amqp.Message m = await receiver.ReceiveAsync(10000);
            if (m != null)
            {
                var id = m.MessageAnnotations.Map[deviceIdKey].ToString();
                if (id == deviceId)
                {
                    Data data = (Data)m.BodySection;
                    string msg = System.Text.Encoding.UTF8.GetString(data.Binary, 0, data.Binary.Length);
                    bool isValid = ValidateMessage(msg);

                    if (isValid)
                    {
                        receiver.Accept(m);
                        Counter.Text = parsedCounter;
                        Debug.Write("Receiving Message " + parsedCounter );
                        TimeText.Text = "The last activity was at " + parsedTime;

                        //Connection String
                        if (connection != null)
                            ConnectedTextBox.Text = "CONNECTED";
                        else
                            ConnectedTextBox.Text = "DISCONNECTED";

                        if (DelayTimer != null)
                            DelayTimer.Cancel();
                    }
                    else
                    {
                        receiver.Release(m);
                    }
                }
            }
        }
    }

我實際上通過使用以下方法解決了這個問題-this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled; -在MainPage的構造函數中。

每次導航到該頁面時,我都會重新初始化該頁面,我認為這導致該頁面與等待的任務失去同步。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM