I port from Java to C # code. There is a fragment:

private void updateWeatherData(final String city) { new Thread() { public void run() { final JSONObject json = WeatherData.getJSONData(getActivity(), city); if (json == null) { _handler.post(new Runnable() { public void run() { Toast.makeText(getActivity(), getActivity().getString(R.string.place_not_found), Toast.LENGTH_LONG).show(); } }); } else { _handler.post(new Runnable() { public void run() { renderWeather(json); } }); } } }.start(); } 

In C #, a stream cannot contain anything, or rather does not take anything that comes after the declaration. That is, if I write this or something similar in the method:

 new thread() 

The compiler will ask you to close the curly braces, although there is a lot of code further. Can you please tell me how to open a stream in order to continue the code in the method without any problems?

    2 answers 2

    The idiomatic method on C # is:

     Task.Run(() => { JSONObject json = ...; if (json == null) { // ... } else { // ... } }); 

    On the other hand, if you need to return execution to the main thread, then it makes sense for you to use async / await, and write something like this:

     async Task updateWeatherData(string city) { var a = getActivity(); var json = await Task.Run(() => WeatherData.getJSONData(a, city)); if (json == null) Toast.makeText(a, a.getString(R.string.place_not_found), Toast.LENGTH_LONG).show(); else renderWeather(json); } 

    See how much easier?

    • one
      Really very good advice, thanks! It seems now everything is much better than it was. There was a moment, instead of getActivity, I used to use earlier (Context, Assets, city) or simply (Context city), in this embodiment it will not work. If I write this.Activity as MainActivity (I’m not writing all this to write all this), will it crash? - BlackerAndrew
    • @BlackerAndrew: I, unfortunately, do not know, I am a complete layman in Android (this is Android, yes?). Sorry! - VladD

    In C #, this can be written as:

     new Thread(() => { // здесь код, выполняемый в потоке }) .Start();