Async version of generic extensions - c#

In C#6 I have the following extensions:
public static void With<T>(this T value, Action<T> action) {
action(value);
}
public static R With<T, R>(this T value, Func<T, R> function) {
return function(value);
}
Is there a way to have Async versions of these extensions?
UPDATE
I am adding an example to clarify. Consider (context is EF context):
IList<Post> posts = context.Posts.With(x => x.ToList());
Now how to do this if I would like to use ToListAsync?
IList<Post> posts = await context.Posts.WithAsync(x => x.ToListAsync());
Or
IList<Post> posts = context.Posts.WithAsync(x => await x.ToListAsync());
What should be the best approach and how would the extension look like?

I will strongly suggest not to use async/await in your extension methods to skip generation of state machine. Just return task and wait or await them when you need them
You can use your second method for async case too
public static R With<T>(this T value, Func<T, R> function)
{
return function(value);
}
Or you can constraint method for only async use
public static R WithAsync<T, R>(this T value, Func<T, R> function)
where R : Task
{
return function(value);
}

I have a blog post on asynchronous delegate types. In summary, the async version of Action<T> is Func<T, Task>, and the async version of Func<T, R> is Func<T, Task<R>>.
I recommend you provide all overloads for maximum usability:
public static void With<T>(this T value, Action<T> action) {
action(value);
}
public static R With<T, R>(this T value, Func<T, R> function) {
return function(value);
}
public static Task With<T>(this T value, Func<T, Task> function) {
return function(value);
}
public static Task<R> With<T, R>(this T value, Func<T, Task<R>> function) {
return function(value);
}

Just do it as with any other function:
public static async Task With<T>(this T value, Func<T, Task> action) {
await action(value);
}
public static async Task<R> With<T, R>(this T value, Func<T, Task<R>> function) {
return await function(value);
}

make it async.
make it return a Task. If you need an actual return type use Task<InsertReturnTypeHere> instead of Task
and for good measure, name it WithAsync. That will allow With<T> to coexist with the async implementation, and it's also common convention.
public static async Task WithAsync<T>(this T value, Action<T> action)
{
await actionAsync(value);
}

public static void With<T>(this T value, Action<T> action) {
action(value);
}
Have your Action schedule a Task itself. With does not expect any value in return so it doesn't have to care how the action is run.
public static R With<T, R>(this T value, Func<T, R> function) {
return function(value);
}
Supply a function which returns a Task. You can use it like var y = await x.With(async z => { /* ... */ });.
Conclusion: you do not need to make any changes.

It depends on the amount of processing you intend to do and how you intent for it to be processed.
Do you need a Thread? If so then using Task provides a good alternative to Thread.
Otherwise there are quite a few threads which may already be available in the Thread Pool for your to use, See this question You can access these threads using 'BeginInvoke'.
static void _TestLogicForBeginInvoke(int i)
{
System.Threading.Thread.Sleep(10);
System.Console.WriteLine("Tested");
}
static void _Callback(IAsyncResult iar)
{
System.Threading.Thread.Sleep(10);
System.Console.WriteLine("Callback " + iar.CompletedSynchronously);
}
static void TestBeginInvoke()
{
//Callback is written after Tested and NotDone.
var call = new System.Action<int>(_TestLogicForBeginInvoke);
//Start the call
var callInvocation = call.BeginInvoke(0, _Callback, null);
//Write output
System.Console.WriteLine("Output");
int times = 0;
//Wait for the call to be completed a few times
while (false == callInvocation.IsCompleted && ++times < 10)
{
System.Console.WriteLine("NotDone");
}
//Probably still not completed.
System.Console.WriteLine("IsCompleted " + callInvocation.IsCompleted);
//Can only be called once, should be called to free the thread assigned to calling the logic assoicated with BeginInvoke and the callback.
call.EndInvoke(callInvocation);
}//Callback
The output should be:
Output
NotDone
NotDone
NotDone
NotDone
NotDone
NotDone
NotDone
NotDone
NotDone
IsCompleted False
Tested
Callback False
Any 'Delegate' type you define can be invoked on the Thread Pool using the 'BeginInvoke' method of the delegate instance. See also MSDN

Related

How to implement my own operator in rx.net

I need the functionality of a hysteresis filter in RX. It should emit a value from the source stream only when the previously emitted value and the current input value differ by a certain amount. As a generic extension method, it could have the following signature:
public static IObservable<T> HysteresisFilter<T>(this IObservable<t> source, Func<T/*previously emitted*/, T/*current*/, bool> filter)
I was not able to figure out how to implement this with existing operators. I was looking for something like lift from RxJava, any other method to create my own operator. I have seen this checklist, but I haven't found any example on the web.
The following approaches (both are actually the same) which seem workaround to me work, but is there a more Rx way to do this, like without wrapping a subject or actually implementing an operator?
async Task Main()
{
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
var rnd = new Random();
var s = Observable.Interval(TimeSpan.FromMilliseconds(10))
.Scan(0d, (a,_) => a + rnd.NextDouble() - 0.5)
.Publish()
.AutoConnect()
;
s.Subscribe(Console.WriteLine, cts.Token);
s.HysteresisFilter((p, c) => Math.Abs(p - c) > 1d).Subscribe(x => Console.WriteLine($"1> {x}"), cts.Token);
s.HysteresisFilter2((p, c) => Math.Abs(p - c) > 1d).Subscribe(x => Console.WriteLine($"2> {x}"), cts.Token);
await Task.Delay(Timeout.InfiniteTimeSpan, cts.Token).ContinueWith(_=>_, TaskContinuationOptions.OnlyOnCanceled);
}
public static class ReactiveOperators
{
public static IObservable<T> HysteresisFilter<T>(this IObservable<T> source, Func<T, T, bool> filter)
{
return new InternalHysteresisFilter<T>(source, filter).AsObservable;
}
public static IObservable<T> HysteresisFilter2<T>(this IObservable<T> source, Func<T, T, bool> filter)
{
var subject = new Subject<T>();
T lastEmitted = default;
bool emitted = false;
source.Subscribe(
value =>
{
if (!emitted || filter(lastEmitted, value))
{
subject.OnNext(value);
lastEmitted = value;
emitted = true;
}
}
, ex => subject.OnError(ex)
, () => subject.OnCompleted()
);
return subject;
}
private class InternalHysteresisFilter<T>: IObserver<T>
{
Func<T, T, bool> filter;
T lastEmitted;
bool emitted;
private readonly Subject<T> subject = new Subject<T>();
public IObservable<T> AsObservable => subject;
public InternalHysteresisFilter(IObservable<T> source, Func<T, T, bool> filter)
{
this.filter = filter;
source.Subscribe(this);
}
public IDisposable Subscribe(IObserver<T> observer)
{
return subject.Subscribe(observer);
}
public void OnNext(T value)
{
if (!emitted || filter(lastEmitted, value))
{
subject.OnNext(value);
lastEmitted = value;
emitted = true;
}
}
public void OnError(Exception error)
{
subject.OnError(error);
}
public void OnCompleted()
{
subject.OnCompleted();
}
}
}
Sidenote: There will be several thousand of such filters applied to as many streams. I need throughput over latency, thus I am looking for the solution with the minimum of overhead both in CPU and in memory even if others look fancier.
Most examples I've seen in the book Introduction to Rx are using the method Observable.Create for creating new operators.
The Create factory method is the preferred way to implement custom observable sequences. The usage of subjects should largely remain in the realms of samples and testing. (citation)
public static IObservable<T> HysteresisFilter<T>(this IObservable<T> source,
Func<T, T, bool> predicate)
{
return Observable.Create<T>(observer =>
{
T lastEmitted = default;
bool emitted = false;
return source.Subscribe(value =>
{
if (!emitted || predicate(lastEmitted, value))
{
observer.OnNext(value);
lastEmitted = value;
emitted = true;
}
}, observer.OnError, observer.OnCompleted);
});
}
This answer is the same is equivalent to #Theodor's, but it avoids using Observable.Create, which I generally would avoid.
public static IObservable<T> HysteresisFilter2<T>(this IObservable<T> source,
Func<T, T, bool> predicate)
{
return source
.Scan((emitted: default(T), isFirstItem: true, emit: false), (state, newItem) => state.isFirstItem || predicate(state.emitted, newItem)
? (newItem, false, true)
: (state.emitted, false, false)
)
.Where(t => t.emit)
.Select(t => t.emitted);
}
.Scan is what you want to use when you're tracking state across items within an observable.

How can I "adapt" a Task<IEnumerable<T>> to IAsyncEnumerable<T>?

I'm incrementally introducing Ix.NET into a legacy project. I have a number of storage-level APIs that return Task<IEnumerable<T>>, but I want to adapt them to IAsyncEnumerable<T> for consumption in the rest of the system. It seems like there should be a helper method (ala .ToAsyncEnumerable() for IEnumerable) to help with this, but I can't find anything... Do I have to implement my own custom Enumerator? (not hard, but I don't want to re-invent the wheel)
Task<IEnumerable<T>> GetSomeResults<T>()
{
throw new NotImplementedException();
}
async IAsyncEnumerable<T> GetAsyncEnumerable<T>()
{
var results = await GetSomeResults<T>();
foreach(var item in results)
{
yield return item;
}
}
If you're talking about web APIs, Task<IEnumerable<T>> is an asynchronous way of producing a IEnumerable<T>.
Regardless of that IEnumerable<T> being produced synchronously or asynchronously, the whole list will be sent as an HTTP response.
The way you could leverage IAsyncEnumerable<T> on the client is if that client is invoking some kind of streaming or making multiple requests to a server for a unique list of results (paging).
I was looking for the exact same thing, and due to the replies here I assume that there is indeed no method like AsAsyncEnumerable(). So here's what I ended up doing, maybe it helps soneone else:
public static class AsyncEnumerableExtensions {
public struct AsyncEnumerable<T> : IAsyncEnumerable<T> {
private readonly IEnumerable<T> enumerable;
public AsyncEnumerable(IEnumerable<T> enumerable) {
this.enumerable = enumerable;
}
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = new CancellationToken()) {
return new AsyncEnumerator<T>(enumerable?.GetEnumerator());
}
}
public struct AsyncEnumerator<T> : IAsyncEnumerator<T> {
private readonly IEnumerator<T> enumerator;
public AsyncEnumerator(IEnumerator<T> enumerator) {
this.enumerator = enumerator;
}
public ValueTask DisposeAsync() {
enumerator?.Dispose();
return default;
}
public ValueTask<bool> MoveNextAsync() {
return new ValueTask<bool>(enumerator == null ? false : enumerator.MoveNext());
}
public T Current => enumerator.Current;
}
public static AsyncEnumerable<T> AsAsyncEnumerable<T>(this IEnumerable<T> that) {
return new AsyncEnumerable<T>(that);
}
public static AsyncEnumerator<T> AsAsyncEnumerator<T>(this IEnumerator<T> that) {
return new AsyncEnumerator<T>(that);
}
}
As commented by Theodor Zoulias,
System.Linq.Async is a NuGet package from .NET Foundation, which supports ToAsyncEnumerable().
Example usage:
var tasks = new Task[0]; // get your IEnumerable<Task>s
tasks.ToAsyncEnumerable();
public static async IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> enumerable)
{
using IEnumerator<T> enumerator = enumerable.GetEnumerator();
while (await Task.Run(enumerator.MoveNext).ConfigureAwait(false))
{
yield return enumerator.Current;
}
}

Best way to define a method which can accept an Action or a Func delegate

I would like to introduce a method/function which can receive an Action or a Func<T>, and depending on what it got, it should return void or T.
Now I have to write this method in two, almost same versions like this.
public void WrapAction(Action action) {
// do something...
action();
// do something more...
}
public T WrapFunc(Func<T> func) {
// do something...
var result = func();
// do something more...
return result;
}
Is there any technique to avoid this repetition?
In contrast, for example in Javascript I have the flexibility to accept any kind of a function (may be void) and just return it's result, and if it was void, then it will return undefined. But in C# one cannot write something like Func<void>.
What about to make an Func<bool> out of an action via an extension method and reduce the wrapper to handle Func<T> only.
public static class ActionExtensions
{
public static Func<bool> ToFunc(this Action action)
{
return () =>
{
action();
return true;
};
}
}
Then WrapAction could simply call WrapFunc.
public void WrapAction(Action action)
{
WrapFunc(action.ToFunc());
}
Or remove WrapAction at all and use WrapFunc directly.
WrapFunc(action.ToFunc());
One possible solution is that you can extract the repeating bits out to separate methods in the same class so, something like this...
public void WrapAction(Action action) {
DoInitialBit();
action();
DoFinalBit();
}
public T WrapFunc(Func<T> func) {
DoInitialBit();
var result = func();
DoFinalBit();
return result;
}
private void DoInitialBit()
{
// Do the thing before you call the Action or Func
}
private void DoFinalBit()
{
// Do the thing after you call the Action or Func
}
Obviously, you may have to take inputs or return outputs from these additional methods as required but that's the general gist of it.
Some really ugly code to have code DRY:
static void Main(string[] args)
{
var p = new Program();
p.WrapAction(() => Console.WriteLine(123));
Console.WriteLine(p.WrapFunc<string>(() => "321"));
Console.ReadKey();
}
public void WrapAction(Action action) => WrapActionInner<object>(action);
public T WrapFunc<T>(Func<T> func) => WrapActionInner<T>(func);
private T WrapActionInner<T>(object action)
{
if (action is Action)
{
((Action)action)();
return default(T);
}
return ((Func<T>)action)();
}
The idea is to wrap functionality into type unsafe private method.

Generic method to map objects of different types

I would like to write Generic Method that would map List to new list, similar to JS's map method. I would then use this method like this:
var words= new List<string>() { "Kočnica", "druga beseda", "tretja", "izbirni", "vodno bitje" };
List<object> wordsMapped = words.Map(el => new { cela = el, končnica = el.Končnica(5) });
I know there's Select method which does the same thing but I need to write my own method. Right now I have this:
public static IEnumerable<object> SelectMy<T>(this IEnumerable<T> seznam, Predicate<T> predicate)
{
List<object> ret = new List<object>();
foreach (var el in seznam)
ret.Add(predicate(el));
return ret;
}
I also know I could use yield return but again I mustn't. I think the problem is with undeclared types and compiler can't figure out how it should map objects but I don't know how to fix that. All examples and tutorials I found map object of same types.
Linq's Select is the equivalent of the map() function in other functional languages. The mapping function would typically not be called Predicate, IMO - predicate would be a filter which could reduce the collection.
You can certainly wrap an extension method which would apply a projection to map input to output (either of which could be be anonymous types):
public static IEnumerable<TO> Map<TI, TO>(this IEnumerable<TI> seznam,
Func<TI, TO> mapper)
{
foreach (var item in seznam)
yield return mapper(item);
}
Which is equivalent to
public static IEnumerable<TO> Map<TI, TO>(this IEnumerable<TI> seznam,
Func<TI, TO> mapper)
{
return seznam.Select(mapper);
}
And if you don't want a strong return type, you can leave the output type as object
public static IEnumerable<object> Map<TI>(this IEnumerable<TI> seznam, Func<TI, object> mapper)
{
// Same implementation as above
And called like so:
var words = new List<string>() { "Kočnica", "druga beseda", "tretja", "izbirni", "vodno bitje" };
var wordsMapped = words.Map(el => new { cela = el, končnica = el.Končnica(5) });
Edit
If you enjoy the runtime thrills of dynamic languages, you could also use dynamic in place of object.
But using dynamic like this so this precludes the using the sugar of extension methods like Končnica - Končnica would either need to be a method on all of the types utilized, or be invoked explicitly, e.g.
static class MyExtensions
{
public static int Končnica(this int i, int someInt)
{
return i;
}
public static Foo Končnica(this Foo f, int someInt)
{
return f;
}
public static string Končnica(this string s, int someInt)
{
return s;
}
}
And then, provided all items in your input implemented Končnica you could invoke:
var things = new List<object>
{
"Kočnica", "druga beseda",
53,
new Foo()
};
var mappedThings = things.Map(el => new
{
cela = el,
končnica = MyExtensions.Končnica(el, 5)
// Or el.Končnica(5) IFF it is a method on all types, else run time errors ...
})
.ToList();
You can fix your code to work correctly like this:
public static IEnumerable<TResult> SelectMy<T, TResult>(this IEnumerable<T> seznam,
Func<T, TResult> mapping)
{
var ret = new List<TResult>();
foreach (var el in seznam)
{
ret.Add(mapping(el));
}
return ret;
}
Note that this is inefficient and problematic compared to typical Linq extensions, because it enumerates the entire input at once. If the input is an infinite series, you are in for a bad time.
It is possible to remedy this problem without the use of yield, but it would be somewhat lengthy. I think it would be ideal if you could tell us all why you are trying to do this task with two hands tied behind your back.
As a bonus, here is how you could implement this with the lazy evaluation benefits of yield without actually using yield. This should make it abundantly clear just how valuable yield is:
internal class SelectEnumerable<TIn, TResult> : IEnumerable<TResult>
{
private IEnumerable<TIn> BaseCollection { get; set; }
private Func<TIn, TResult> Mapping { get; set; }
internal SelectEnumerable(IEnumerable<TIn> baseCollection,
Func<TIn, TResult> mapping)
{
BaseCollection = baseCollection;
Mapping = mapping;
}
public IEnumerator<TResult> GetEnumerator()
{
return new SelectEnumerator<TIn, TResult>(BaseCollection.GetEnumerator(),
Mapping);
}
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
internal class SelectEnumerator<TIn, TResult> : IEnumerator<TResult>
{
private IEnumerator<TIn> Enumerator { get; set; }
private Func<TIn, TResult> Mapping { get; set; }
internal SelectEnumerator(IEnumerator<TIn> enumerator,
Func<TIn, TResult> mapping)
{
Enumerator = enumerator;
Mapping = mapping;
}
public void Dispose() { Enumerator.Dispose(); }
public bool MoveNext() { return Enumerator.MoveNext(); }
public void Reset() { Enumerator.Reset(); }
public TResult Current { get { return Mapping(Enumerator.Current); } }
object IEnumerator.Current { get { return Current; } }
}
internal static class MyExtensions
{
internal static IEnumerable<TResult> MySelect<TIn, TResult>(
this IEnumerable<TIn> enumerable,
Func<TIn, TResult> mapping)
{
return new SelectEnumerable<TIn, TResult>(enumerable, mapping);
}
}
The problem with your code is that Predicate<T> is a delegate that returns a boolean, which you're then trying to add to a List<object>.
Using a Func<T,object> is probably what you're looking for.
That being said, that code smells bad:
Converting to object is less than useful
Passing a delegate that maps T to an anonymous type won't help - you'll still get an object back which has no useful properties.
You probably want to add a TResult generic type parameter to your method, and take a Func<T, TResult> as an argument.

Asynchronously invoking a method with an output parameter

Is it possible to use a TPL Task<TResult> to asynchronously invoke a thread-safe method with the following signature and retrieve the boolean return value and the output parameter?
public bool TryGet(T1 criteria,
out T2 output)
Obviously I can't use a lambda expression because of the output parameter. Additionally, I cannot solve the problem by defining a custom delegate such as below and passing that to the Task<TResult> constructor as I need to pass the criteria as a strongly typed parameter which the constructor does not support.
public delegate TResult Func<T1, T2, TResult>(T1 arg1,
out T2 arg2);
Is the best option to write a wrapper such as below and invoke that asynchronously instead?
public Tuple<bool, T2> TryGetWrapper(T1 criteria)
{
T2 output;
bool result = obj.TryGet(criteria,
out output);
return new Tuple<bool, T2>(result,
output);
}
Just seems a bit inelegant and has a bit of a whiff about it.
This is something I've also wrestled with.
I came up with a similar solution, except rather than use a Tuple I wrote a simple wrapper class, just to make things a bit more readable.
I'd also be interested to see any better solution - but what you propose seems as good as anything I came up with.
Here's what my wrapper class and its usage looks like. This is not an answer to your question; just a suggestion to (perhaps) make your solution a bit more readable.
(Although I concede that the Task<TryResult<DateTime>> declaration itself might not be considered all that readable!)
using System;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
internal class Program
{
static void Main()
{
string dateString = "Invalid Date";
var tryParseDateTask = new Task<TryResult<DateTime>>(() =>
{
DateTime result;
if (DateTime.TryParse(dateString, out result))
return TryResult<DateTime>.Success(result);
else
return TryResult<DateTime>.Failure();
});
tryParseDateTask.Start();
if (tryParseDateTask.Result.IsSuccessful)
Console.WriteLine(dateString + " was parsed OK.");
else
Console.WriteLine(dateString + " was parsed as " + tryParseDateTask.Result.Value);
}
}
public class TryResult<T>
{
public static TryResult<T> Success(T value)
{
return new TryResult<T>(value, true);
}
public static TryResult<T> Failure()
{
return new TryResult<T>(default(T), false);
}
TryResult(T value, bool isSuccessful)
{
this.value = value;
this.isSuccessful = isSuccessful;
}
public T Value
{
get
{
return value;
}
}
public bool IsSuccessful
{
get
{
return isSuccessful;
}
}
readonly T value;
readonly bool isSuccessful;
}
}
I think your approach is pretty much the best you can do. If you are doing this often, you could use a helper method that convert a delegate with out parameter to a Tuple-returning delegate (or something like TryResult-returning, as in Matthew Watson's answer):
public delegate TResult OutFunc<TIn, TOut, TResult>(TIn input, out TOut output);
public static Func<TIn, Tuple<TResult, TOut>> OutToTuple<TIn, TOut, TResult>(
OutFunc<TIn, TOut, TResult> outFunc)
{
return input =>
{
TOut output;
TResult result = outFunc(input, out output);
return Tuple.Create(result, output);
};
}

Categories

Resources