Azure Functions: ICollector<T> vs IAsyncCollector<T>

Chris Gillum picture Chris Gillum · Nov 22, 2016 · Viewed 9k times · Source

What's the difference between ICollector<T> and IAsyncCollector<T> in Azure Functions when writing C# functions (also applies to WebJobs)?

I understand from the samples that these are interfaces I can use to bind a function parameter to an output binding. I also understand that the two interfaces have non-async and async method signatures accordingly (i.e. ICollector<T>.Add(item) and IAsyncCollector<T>.AddAsync(item)). But what do they do under the covers? Do they actually post data to the output binding, or is it internally buffered and flushed at the end of function execution (in which case, why would there by an AddAsync method)?

Answer

mathewc picture mathewc · Nov 22, 2016

ICollector<T>.Add(item) will always perform the add operation against the underlying service immediately. E.g. the implementation for the Queue binding will enqueue messages immediately as they are added.

IAsyncCollector<T>.AddAsync(item) behavior varies from binding to binding, based on whether the underlying service supports batching. In such cases, AddAsync may only actually save the added items to be flushed later by the corresponding IAsyncCollector<T>.FlushAsync method. When a function completes successfully FlushAsync will be called automatically. You can allow the auto-flush behavior to flush for you, or you may choose to call FlushAsync manually in your function as you need to.

Batching can allow the binding to interact with the underlying service in the most efficient way possible. E.g. for Azure Tables, multiple entities can be updated/persisted in a single batch operation.