Proper CloudTableClient instance lifecycle?
Asked Answered
S

4

19

I'm using the new WindowsAzure.Storage 2.0 (might not be a revelant information), and I'm implementing data access using CloudTableClient. Most samples I've seen are instanciating a CloudTableClient in the ctor of an ASP MVC Controller (instanciated per web request). Is there any performance penalty doing so? Would it be wise to keep a long running instance in a singleton style?

Sayette answered 5/1, 2013 at 7:8 Comment(0)
A
14

You need to create a new instance of CloudTableClient with each request. Instance members are not thread-safe, so you can't share a singleton.

Ammons answered 5/1, 2013 at 7:22 Comment(3)
Hi, it looks like the link is broken if you have time to find the equivalent info in the new documentation - although I see the answer is way back in 2013!.Appal
Weird, because the documentation on learn.microsoft.com/en-us/azure/azure-functions/… says: "To avoid holding more connections than necessary, reuse client instances rather than creating new ones with each function invocation. We recommend reusing client connections for any language that you might write your function in. For example, .NET clients like the HttpClient, DocumentClient, and Azure Storage clients can manage connections if you use a single, static client." And CloudTableClient is a "Azure Storage Client"Certifiable
To be fair, my answer was 6 years ago. Things might have changed.Ammons
A
3

I came across this question / answer wondering the same thing and whilst looking through the SDK's source code (for something else) I came across something useful:

When executing an operation, the SDK is using a HttpClientFactory, so a single static instance of HttpClient is being reused. Which is good, and corrects the Improper Instantiation antipattern, so the common reason to use a singleton is already sorted for us.

Relevant code can be found on github During Execution and the HttpClient factory is implemented via a static Lazy<T>

Notably the Storage SDK doesn't support Table anymore (instead the Cosmos SDK appears to provide it - I'm learning more), so this is likely a moot observation.

Appal answered 5/3, 2019 at 15:36 Comment(0)
U
3

I think in 2020 you should reuse.

https://azure.microsoft.com/en-us/blog/performance-tips-for-azure-documentdb-part-1-2/

Untrimmed answered 14/4, 2020 at 20:54 Comment(0)
S
0

Looking at CloudTableClient documentation, I realize it's not thread safe.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Hence it is probably required to instanciate it for each request.

Sayette answered 5/1, 2013 at 7:21 Comment(1)
Yep, posted just as you answered. There's no performance penalty with doing it.Ammons

© 2022 - 2024 — McMap. All rights reserved.