Xamarin displayalert не отображается - PullRequest
1 голос
/ 25 февраля 2020

У меня есть xamarin форма приложения, и я подключил его signalr не работает моя пустота. Я искал на inte rnet, но ничего не могу найти по этому поводу. И это мой код Myhub.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR.Client;

namespace PharmClient
{
    class MyHub
    {
        string url = "https://webapplication11-co5.conveyor.cloud/";
        HubConnection Connection;
        IHubProxy ProxyOFServer;
        public delegate void Error();
        public delegate void MessageRecieved(string _data);
        public event Error CoonectionError;
        public event MessageRecieved OndataRecieved;
        public delegate void Completed();
        public event Completed OnCompleted;

        public void Connect()
        {
            Connection = new HubConnection(url);
            ProxyOFServer = Connection.CreateHubProxy("MuHub");
            Start().ContinueWith(task => { if (task.IsFaulted) { CoonectionError?.Invoke(); } else { OnCompleted?.Invoke(); }  });

        }

        public Task Start()
        {
            return Connection.Start();
        }
        public void SendData(string data)
        {
            ProxyOFServer.Invoke<string>("SendMessage", data);
        }

        public void Recive( )
        {
            ProxyOFServer.On<string>("Sentdata", data => { OndataRecieved?.Invoke(data); });
        }
    }
}

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using System.Threading;
namespace PharmClient
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        MyHub ConnectServer = new MyHub();
        public  MainPage()
        {
            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);
            ConnectServer.OnCompleted += ConnectServer_OnCompleted;
            ConnectServer.CoonectionError += ConnectServer_CoonectionError;

             ConnectServer.Connect();
        }

        private void ConnectServer_OnCompleted()
        {
            DisplayAlert("Connected", "Good", "O");
        }

        private void ConnectServer_CoonectionError()
        {
            DisplayAlert("Failed", "Bad", "Ok");
        }

        private void SerchDrug_Clicked(object sender, EventArgs e)
        {
            Navigation.PushAsync(new SearchDrug());
        }
    }
}

При сбое соединения ConnectionError событие выполнено, но соединение будет успешно OnCompleted событие не будет запущено. Я студент. Это часть групповой работы. В чем проблема моего кода любой справки. Я не могу ничего найти. Спасибо за внимание

Ответы [ 2 ]

1 голос
/ 25 февраля 2020

Как следует из названия, у вас есть проблема с отображением диалогового окна.

Попробуйте просмотреть документацию ( здесь ) один раз для полного понимания, вам нужно await процесс отображения DisplayAlert.

Добавьте await & async к вашим методам.

Попробуйте это -

        private async void ConnectServer_OnCompleted()
        {
            await DisplayAlert("Connected", "Good", "O");
        }

        private async void ConnectServer_CoonectionError()
        {
            await DisplayAlert("Failed", "Bad", "Ok");
        }

Если у вас есть какие-то вопросы, касающиеся, дайте мне знать.

0 голосов
/ 25 февраля 2020

Вам следует дождаться соединения, не запустить и забыть. Пример:

    private HubConnection connection;
    private IHubProxy proxy;
    public event EventHandler<ChatMessageObject> OnMessageReceived;

    public async Task Connect()
    {
        try
        {
            await connection.Start();

            await proxy.Invoke("Connect"); // example method in your backend

            proxy.On("messageReceived", (int userId, string name, string message, DateTime messageDateTime) => OnMessageReceived(this, new ChatMessageObject
            {
                FromUserId = userId,
                UserName = name,
                MessageText = message,
                MessageDateTime = messageDateTime
            }));
        }
        catch (Exception ex)
        {
            //handle exceptions
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...