C# 如何创建背景线程

C# 如何创建背景线程,c#,android,json,multithreading,C#,Android,Json,Multithreading,我目前正在开发一款移动android应用程序。此应用程序在加载时间上遇到的主要问题是Webservice json字符串,在当前阶段加载该字符串花费的时间太长,有时会导致应用程序强制关闭(暂停时间太长) Splash->MainActivity->HomeActivity这就是应用程序的启动方式 首先,我们显示一个Splash,然后运行MainActivity,它由以下代码组成: public class HomeActivity : Activity { NewsObject[] n

我目前正在开发一款移动android应用程序。此应用程序在加载时间上遇到的主要问题是Webservice json字符串,在当前阶段加载该字符串花费的时间太长,有时会导致应用程序强制关闭(暂停时间太长)

Splash->MainActivity->HomeActivity这就是应用程序的启动方式

首先,我们显示一个Splash,然后运行MainActivity,它由以下代码组成:

public class HomeActivity : Activity
{

    NewsObject[] news;

    protected override void OnCreate (Bundle bundle)

    {

        base.OnCreate (bundle);



        SetContentView (Resource.Layout.Main);



        var request = HttpWebRequest.Create(string.Format(@"http://rapstation.com/webservice.php"));

        request.ContentType = "application/json";

        request.Method = "GET";



        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)

        {

            if (response.StatusCode != HttpStatusCode.OK)

                Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))

            {

                var content = reader.ReadToEnd();

                if(string.IsNullOrWhiteSpace(content)) {

                    Console.Out.WriteLine("Response contained empty body...");

                    Toast toast = Toast.MakeText (this, "No Connection to server, Application will now close", ToastLength.Short);

                    toast.Show ();

                }

                else {

                    news = JsonConvert.DeserializeObject<NewsObject[]>(content);

                }

            }

            Console.Out.WriteLine ("Now: \r\n {0}", news[0].title);

        }



        var list = FindViewById<ListView> (Resource.Id.list);

        list.Adapter = new HomeScreenAdapter (this, news);

        list.ItemClick += OnListItemClick;



        var Listen = FindViewById<Button> (Resource.Id.btnListen);

        var Shows  = FindViewById<Button> (Resource.Id.btnShows);



        Listen.Click += (sender, e) => {

            var second = new Intent (this, typeof(RadioActivity));

            StartActivity (second);

        };



        Shows.Click += (sender, e) => {

            var second = new Intent (this, typeof(ShowsActivity));

            StartActivity (second);

        };

    }



    protected void OnListItemClick(object sender, AdapterView.ItemClickEventArgs e)

    {

        var listView = sender as ListView;

        var t = news[e.Position];

        var second = new Intent (this, typeof(NewsActivity));

        second.PutExtra ("newsTitle", t.title);

        second.PutExtra ("newsBody", t.body);

        second.PutExtra ("newsImage", t.image);

        second.PutExtra ("newsCaption", t.caption);

        StartActivity (second);



        Console.WriteLine("Clicked on " + t.title);

    }

}
公共类家庭活动:活动
{
新闻对象[]新闻;
创建时受保护的覆盖无效(捆绑包)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
var request=HttpWebRequest.Create(string.Format)(@)http://rapstation.com/webservice.php"));
request.ContentType=“application/json”;
request.Method=“GET”;
使用(HttpWebResponse=request.GetResponse()作为HttpWebResponse)
{
if(response.StatusCode!=HttpStatusCode.OK)
Console.Out.WriteLine(“获取数据时出错。服务器返回状态代码:{0}”,response.StatusCode);
使用(StreamReader=newstreamreader(response.GetResponseStream())
{
var content=reader.ReadToEnd();
if(string.IsNullOrWhiteSpace(content)){
Console.Out.WriteLine(“响应包含空体…”);
Toast Toast=Toast.MakeText(这是“没有连接到服务器,应用程序现在将关闭”,ToastLength.Short);
toast.Show();
}
否则{
news=JsonConvert.DeserializeObject(内容);
}
}
Console.Out.WriteLine(“现在:\r\n{0}”,新闻[0]。标题);
}
var list=findviewbyd(Resource.Id.list);
list.Adapter=newhomescreenadapter(这是新闻);
list.ItemClick+=OnListItemClick;
var Listen=findviewbyd(Resource.Id.btnListen);
var Shows=findviewbyd(Resource.Id.btnShows);
听。点击+=(发送者,e)=>{
var second=新意图(此,放射性类型);
星触觉(秒);
};
显示。单击+=(发件人,e)=>{
var second=新意图(此,类型(ShowsActivity));
星触觉(秒);
};
}
受保护的void OnListItemClick(对象发送者,AdapterView.ItemClickEventArgs e)
{
var listView=发送方作为listView;
var t=新闻[e.位置];
var second=新意图(此,类型为(NewsActivity));
第二个标题(“新闻标题”,t.title);
第二,PutExtra(“新闻正文”,t.body);
第二,PutExtra(“newsImage”,t.image);
第二,PutExtra(“新闻标题”,t.caption);
星触觉(秒);
Console.WriteLine(“单击”+t.title);
}
}
我遇到的问题是,应用程序会粘在启动页面上,应用程序输出会告诉我,我在主线程上运行了太多


什么是分离下载请求以在后台工作的方法?

是的,有,您需要使用,也应该有帮助。

如果您使用的.Net/Mono版本支持,那么您可以简单地执行

private class myTask extends AsyncTask<Void, Void, Void> {


        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(Void... params) {
            // Runs on the background thread


            return null;
        }

        @Override
        protected void onPostExecute(Void res) {

        }

    }
async void DisplayNews()
{
    string url = "http://rapstation.com/webservice.php";

    HttpClient client = new HttpClient();
    string content = await client.GetStringAsync(url);
    NewsObject[] news = JsonConvert.DeserializeObject<NewsObject[]>(content);
    //!! Your code to add news to some control
}
async void DisplayNews()
{
字符串url=”http://rapstation.com/webservice.php";
HttpClient=新的HttpClient();
string content=wait client.GetStringAsync(url);
NewsObject[]news=JsonConvert.DeserializeObject(内容);
//!!将新闻添加到某些控件的代码
}
如果没有,那么您可以使用的

void DisplayNews2()
{
字符串url=”http://rapstation.com/webservice.php";
Task.Factory.StartNew(()=>
{
使用(var client=new WebClient())
{
字符串内容=client.DownloadString(url);
返回JsonConvert.DeserializeObject(内容);
}
})
.ContinueWith((任务,y)=>
{
NewsObject[]news=task.Result;
//!!将新闻添加到某些控件的代码
},null,TaskScheduler.FromCurrentSynchronizationContext());
}

我已经研究过asynctask,但每次我尝试以您链接的指南所示的方式实现它时,都会发现错误,缺少指令和当前上下文中不存在的内容。您能更具体一点吗?我可能可以帮助您啊,所以我对子类化不是很确定,但这似乎对asynctask相当重要。去解决这个问题吧,谢谢你的帮助!啊哈!当我试图创建这个类时,它给了我一个错误,在顶部说意外的符号“extends”。我该如何解决这个问题?我在标记中特别指出,这是在C#中,因此如果您上面提供的代码是在Java中,我不会是更明智的。为什么您要在Java android线程中发布,而不提及您需要它在C#中编译的事实?选择只使用标记?
async void DisplayNews()
{
    string url = "http://rapstation.com/webservice.php";

    HttpClient client = new HttpClient();
    string content = await client.GetStringAsync(url);
    NewsObject[] news = JsonConvert.DeserializeObject<NewsObject[]>(content);
    //!! Your code to add news to some control
}
void DisplayNews2()
{
    string url = "http://rapstation.com/webservice.php";

    Task.Factory.StartNew(() =>
        {
            using (var client = new WebClient())
            {
                string content = client.DownloadString(url);
                return JsonConvert.DeserializeObject<NewsObject[]>(content);
            }
        })
    .ContinueWith((task,y) =>
        {
            NewsObject[] news = task.Result;
            //!! Your code to add news to some control
        },null,TaskScheduler.FromCurrentSynchronizationContext());
}