比如我有类public static NetHelper
{
    public static getVersion()
    {
        int version = getNetVersion();//这里从网络上取得网上的版本
    }
}上面的类在线程中调用是没有问题的,但在主线程调用就会出错
那在不更改主线程业务的情况下,
如何修改这个GetVersion方法,那他可以在主线程,也可以在子线程中调用呢?万分感谢

解决方案 »

  1.   

    因为这个GetVersion是要访问网络的
    Android4.0 以后不允许在主线程进行网络连接,否则会出现 android.os.NetworkOnMainThreadException
    ----------------------------
    然后我现在这个类又有可能给子线程和主线程调用,
    现在要求在不改变其他业务流程,只改动这个GetVersion方法,
    有没有办法让这个方法可以让主线程也进行调用
    谢谢
      

  2.   

    问题是我要去异步访问网络,又要在主线程同步回来
    我试过用CountDownLatch来等待线程返回
    但是这样又可能会出现 主线程成时间不响应而就用崩溃的情况
      

  3.   

    这样试试        public static class NetHelper
            {
                internal sealed class proxy
                {
                    private object waitLock = new object();
                    private int version;
                    private bool isValue;
                    private void getNetVersion()
                    {
                        version = NetHelper.getNetVersion();
                        Monitor.Enter(waitLock);
                        try
                        {
                            isValue = true;
                            Monitor.Pulse(waitLock);
                        }
                        finally { Monitor.Exit(waitLock); }
                    }
                    private int wait()
                    {
                        Monitor.Enter(waitLock);
                        try
                        {
                            if (!isValue) Monitor.Wait(waitLock);
                        }
                        finally { Monitor.Exit(waitLock); }
                        return version;
                    }
                    public static int GetNetVersion()
                    {
                        proxy proxy = new proxy();
                        new Thread(proxy.getNetVersion).Start();//当然最好是丢在线程池里面
                        return proxy.wait();
                    }
                }
                private static int getNetVersion() { return 0; }//这里从网络上取得网上的版本
                public static void getVersion()
                {
                    int version = proxy.GetNetVersion();
                    Console.WriteLine(version.toString());
                }
            }
      

  4.   

    在android里面,你去网络访问获取版本号的时候需要新开一个线程去做
      

  5.   

    使用fastCSharp的话,可以这样            int version = fastCSharp.threading.task.Default.Add(getNetVersion).Return;