alundy
alundy

Reputation: 857

WCF service running a background thread to speed up execution time

I have a per-call WCF service that serves a number of clients. I'm looking to speed up the services by running some background processes so they don't block or slow down the main function of the services.

One example is that the main function needs to return a set of data, while the background thread needs to record some statistics based on the parameter(s).

Code:

Public Function GetAccountDetails(id As Integer) As AccountDetails

    Dim retVal As New AccountDetails
    Dim a As New Accounts
    retVal = a.GetAccountDetails(id)

    Dim t As New Thread(New ThreadStart(Sub()
                                             Dim s As New Statistic
                                             s.StatisticType = StatisticType.GetAccount
                                             s.Parameter = id.ToString
                                             s.Record()
                                        End Sub))
    t.Start()

    Return retVal

End Function

If I use this background thread to record the statistic it doesn't block the main thread from returning the data to the client.

It's been working well in test scenarios, but my question is, are there any dangers with leaving this thread to execute without Joining it before returning the data to the client? Could there potentially be any loss of statistic data? Could there be potential memory problems on the server side?

Thanks.

Upvotes: 3

Views: 1189

Answers (1)

Jeremy McGee
Jeremy McGee

Reputation: 25210

This approach, which is a sort of "delayed write" pattern, is not unusual.

The main issues are:

  • You won't get a coherent view of the Statistics table, it'll always lag the actual usage. This "eventual consistency" is usually very appropriate for logging or statistics but not for updates that need to be transactionally correct.

  • There's no mechanism for handling errors during the statistics table update: the calling service will continue, blissfully unaware of the problem. This may not be a problem for your situation: if all you'd do anyway is log-and-continue then you can continue with that same strategy

  • If your service becomes very busy you'll spawn off lots of threads that swamp your server.

This last point may be addressed by introducing a queue (something like MSMQ is fine) to take statistic update request messages and a worker service that can process the requests. Then you can throttle the number of updates processed in one go. This does add to the complexity of the architecture (and testing!) but makes your system more predictably scalable, especially if your traffic isn't a single consistent flow.

Upvotes: 2

Related Questions