【问题标题】:Accessing UI thread in Xamarin Android在 Xamarin Android 中访问 UI 线程
【发布时间】:2021-12-04 07:36:41
【问题描述】:

我的应用程序发送和接收 TCP 字符串。其中一个字符串是根据字符串使对象可见。我当前的代码给了System.NullReferenceException has been thrown 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. 

【问题讨论】:

    标签: c# multithreading xamarin xamarin.android


    【解决方案1】:

    您必须在构造函数中将上下文传递给您的类

    所以你可以向你的类添加一个构造函数,比如:

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

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

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

    【讨论】:

      猜你喜欢
      • 2010-10-17
      • 1970-01-01
      • 2015-01-13
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 2020-07-07
      • 2016-09-17
      相关资源
      最近更新 更多