I write a network chat client app with Xamarin.Forms.
To build network receive loop I need to run it at a async function.
In the function 'Device.BeginInvokeOnMainThread' I want to invoke the 'MainPage.SendButton_Clicked' but there is no instance for me to reference it.
I want to know how to do this in Xamarin.Forms is recommended.
public partial class App : Application
{
...
public App()
{
...
MainManager.StartWorkThread();
}
...
}
class MainManager
{
public static void StartWorkThread()
{
System.Threading.Tasks.Task.Run(() =>
{
int n = 0;
while(true)
{
n++;
int id = Thread.CurrentThread.ManagedThreadId;
Debug.WriteLine("MainManager.cs CurrentThreadId = {0} [{1}]", id, n);
Thread.Sleep(3000);
Device.BeginInvokeOnMainThread(() =>
{
// I don't know how to invoke the MainPage.SendButton_Clicked at here
});
}
});
}
}
public partial class MainPage : ContentPage
{
public ObservableCollection<TextMessage> textMessages;
public MainPage()
{
InitializeComponent();
textMessages = new ObservableCollection<TextMessage>();
for (int i = 0; i < 30; i++)
{
var msg = new TextMessage();
msg.Nickname = "我的六字昵称";
msg.Ip = "127.0.0.1";
msg.Message = "这是一条聊天信息";
msg.MessageNumber = i + 1;
textMessages.Add(msg);
}
this.BindingContext = textMessages;
}
private void SendButton_Clicked(object sender, EventArgs e)
{
var msg = new TextMessage();
msg.Nickname = "我的六字昵称";
msg.Ip = "127.0.0.1";
msg.Message = sendText.Text;
msg.MessageNumber = 100;
textMessages.Add(msg);
sendText.Text = "";
listView.ScrollTo(msg, ScrollToPosition.End, true);
}
}