I am dedicated to developing for Android but now I am involved in a project that involves development for Desktop in C#
Some time ago I had created this class that extends the AsyncTask class, what this class does is do a GET to a url and return the result as a jsonString
blic class LectorJsonHttp extends AsyncTask<String, Void, String> {
private LectorJsonHttpResultado lectorJsonHttpResultado;
boolean lecturaCorrecta = false;
public LectorJsonHttp(LectorJsonHttpResultado lectorJsonHttpResultado) {
this.lectorJsonHttpResultado=lectorJsonHttpResultado;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... httpUrl) {
String jsonString="error";
try {
StrictMode.ThreadPolicy Policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(Policy);
HttpClient objCliente = new DefaultHttpClient();
HttpContext objContext = new BasicHttpContext();
HttpGet objGet = new HttpGet(httpUrl[0]);
HttpResponse objResponse = objCliente.execute(objGet, objContext);
HttpEntity objEntidad = objResponse.getEntity();
jsonString = EntityUtils.toString(objEntidad, "UTF-8");
if(!jsonString.equals("error"))lecturaCorrecta = true;
}catch (Exception E)
{
lecturaCorrecta = false;
}
return jsonString;
}
@Override
protected void onPostExecute(String jsonString) {
lectorJsonHttpResultado.abstractMtdJsonString(jsonString,lecturaCorrecta);
super.onPostExecute(jsonString);
}
Now in the c# project I need to do the same thing, I have researched for a long time but I don't find something really understandable since asynchronous tasks in C# don't have a postExecute method that can be used to send data to the main thread through an Interface, I hope that you can give me some advice or a clue to be able to do this, thanks in advance
For asynchronous programming there are several options in C#. You can use
BackGroundWorker
or as you have already been told in a comment,Task
. I would recommend the latter since it is more modern and powerful.For the case you expose, the only thing you need is to use
HttpClient
in an asynchronous method. Here is a very simple example of how to download a page usingGetAsync
andTask
: