gpt4 book ai didi

c# - 在 Xamarin Android 中访问 UI 线程

转载 作者:行者123 更新时间:2023-12-05 05:15:58 25 4
gpt4 key购买 nike

我的应用程序发送和接收 TCP 字符串。其中一个字符串是根据字符串使对象可见。我当前的代码给出 System.NullReferenceException has been throwed Object reference not set to an instance of an object.

我找不到正确的访问方法,我猜是因为 RunOnUI 似乎没有访问权限。

我当前的代码:

听众类:(完整类的片段,如果需要我可以发布更多)。

public void ReadCallback(IAsyncResult ar)
{
MainActivity ma = new MainActivity();
String content = string.Empty;

StateObject so = (StateObject)ar.AsyncState;
Socket handle = so.workSocket;

int bytesRead = handle.EndReceive(ar);

if (bytesRead > 0)
{
so.sb.Append(System.Text.Encoding.ASCII.GetString(so.buffer, 0, bytesRead));
content = so.sb.ToString();
}
if (content.IndexOf("0") > -1)
{
ma.RunOnUiThread(() =>
{
//This is where the received data is passed
ma.SortData(content);
});
Send(handle, content);
}
else
{
handle.BeginReceive(so.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), so);
}
}

以及 SortData 的代码:

public void SortData(string data)
{
if(data == "0")
{
txtmsg.Visibility = ViewStates.Invisible;
}
} //This is the only code that's called, the txtmsg.Visibility part is the error producer once called.

最佳答案

您必须在构造函数中将 Context 传递给您的类

所以你会在你的类中添加一个构造函数,比如:

MainActivity mContext;

public YourClass(MainActivity context) {
this.mContext = context;
}

然后从您的类中调用该方法,例如:

mContext.RunOnUiThread(() =>
{
//This is where the received data is passed
mContext.SortData(content);
});

关于c# - 在 Xamarin Android 中访问 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50973167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com