Search code examples
c#background-process

Best practice to execute background task in c#


I'd like to know what is the best practice to execute background task in c#?

For example, in my application I have a save() function, and when I execute this function, I'd like to run another task in background - in my case, using google maps geocoder to convert address in lat/lng.


Solution

  • I suggest that you collect and/or calculate all the information you need to save before you save it.

    Consider this: If the conversion from address to lat/lng fails. Should the Save() method actually save the object or not? I would recommend that you put that logic somewhere else than in the Save() method.

    You could do like this:

    // example object
    private ObjectToSave PrepareObjectForPersistance()
    {
        return new ObjectToSave { LatLng = await ConvertAddressToLatLng(address) };
    }
    

    Then pass the object you want to save to the Save() method:

    public void Save(ObjectToSave obejctToSave)
    {
        // Do whatever has to be done to save your object
    }