0

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.

afuzzyllama
  • 6,538
  • 5
  • 47
  • 64
Vincent Ducroquet
  • 864
  • 4
  • 14
  • 24
  • 2
    have you heard of task objects? – David Haim Mar 22 '17 at 08:41
  • 2
    google for BackgroundWorker, Task, async/await – Backs Mar 22 '17 at 08:42
  • yes i know them but is there a best way to answer my case? Is there any outdated way ? Is it better for a project to use async/await, or task instead of background worker? that's my question thanks^^ – Vincent Ducroquet Mar 22 '17 at 08:46
  • 1
    @PJvG, Parallel programming have nothing to do with OP's question. OP's want access external resources without blocking UI. For this purpose `async-await` is a best approach in .NET. Which will not create new threads and will not use other cores for processing data. – Fabio Mar 22 '17 at 08:55
  • @Fabio Yes you're right. It's better to keep it simple and just use `async` and `await`. However, if you want another approach, it's also an option to use [Task-based Asynchronous Programming](https://msdn.microsoft.com/en-us/library/dd537609(v=vs.110).aspx). – PJvG Mar 22 '17 at 09:06
  • The following question might also be of help: http://stackoverflow.com/questions/35987375/always-use-the-async-and-await-keywords-in-asynchronous-methods-in-a-library (and I think might possibly even be considered a duplicate question to this question.) – PJvG Mar 22 '17 at 09:11
  • 2
    @PJvG, you can use Task-based asynchronous programming, but it will be in some way waste of resources/threads. Because "background" thread will do nothing - only waiting for response. That is why `async-await` can be considered good approach for working with external resources. – Fabio Mar 22 '17 at 09:12
  • 1
    I'd use Microsoft's Reactive Framework (NuGet System.Reactive). It's far more powerful than TPL or any other option presented so far. – Enigmativity May 21 '17 at 02:05

1 Answers1

2

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
} 
DevJoe
  • 419
  • 3
  • 17