So basically T has a return type, I want to get back the generic return type. Example:
private TResult EndInvoke<T, TResult>(Func<T, TResult> asyncCaller, IAsyncResult asyncResult)
{
TResult result = default(TResult);
try
{
result = asyncCaller.EndInvoke(asyncResult);
}
catch (Exception exception)
{
// get exception details.
}
return result;
}
How do I pass just the T calling the method and get the TResult?
Mind you, I only have the T.
EDIT: I meant how do I call this method?
EDIT: I want a generic EndInvoke, because I am a huge try catch on different EndInvokes, then I want the result from the EndInvoke.
I suggest converting your generic EndInvoke<,> method to an extension method first.
public static class FuncExtensions
{
public static TResult EndInvoke<T, TResult>(this Func<T, TResult> asyncCaller, IAsyncResult asyncResult)
{
// ...
}
}
This will simplify the method call. As an example, I'll call a method that calculates the square of an integer.
private int Square(int x)
{
return x * x;
}
In your client code, you'd call it like this:
Func<int, int> caller = new Func<int, int>(Square);
int x = 5;
int y = default(int);
caller.BeginInvoke(x,
asyncResult =>
{
y = caller.EndInvoke(asyncResult);
},
null);
Console.WriteLine("The square of {0} is {1}", x, y);
EDIT
This example has not been tested in any way, and contains an obvious race condition.
Not sure that I understand correctly, but I think that if you want the Func return value, you should drop the IAsyncResult.
Example:
private TResult GetResult<T, TResult>(Func<T, TResult> asyncCaller, IAsyncResult asyncResult)
{
TResult result = default(TResult);
result = asyncCaller(argument...);
return result;
}
Related
I try to implement a decorator pattern for handling error in database transactions. I have no problem with standard Func and Actions, but i have difficulties with functions having out parameter.
Here many topics with same question, and i figured out to implement my own delegate:
public delegate TResult FuncWithOut<T1, T2, TResult>(T1 arg1, out T2 arg2);
1) But i don't found how to implement method based on this delegate:
private void SafetyExecuteMethod(Action action)
{
try
{
action();
}
catch (Exception ex)
{
// Some handling
}
}
private T SafetyExecuteFunction<T>(Func<T> func)
{
T result = default(T);
SafetyExecuteMethod(() => result = func.Invoke());
return result;
}
private SafetyExecuteFunctionWithOut // ??
{
// ??
}
2) And how to call this method:
public bool UserExists(string name)
{
return SafetyExecuteFunction(() => _innerSession.UserExists(name));
}
public void CreateUser(string name, string password)
{
SafetyExecuteMethod(() => _innerSession.CreateUser(name, password));
}
public bool CanUpdateUser(string userName, out string errorMessage)
{
// ??
// _innerSession.CanUpdateUser(userName, out errorMessage);
}
Just use the same scheme as in your example of SafetyExecuteFunction<T>(Func<T> func).
One thing you have to pay attention to is that you need to use a temporary local variable for the out parameter.
private TResult SafetyExecuteFunctionWithOut<T1, T2, TResult>(FuncWithOut<T1, T2, TResult> func, T1 arg1, out T2 arg2)
{
TResult result = default(TResult);
T2 arg2Result = default(T2); // Need to use a temporary local variable here
SafetyExecuteMethod(() => result = func(arg1, out arg2Result));
arg2 = arg2Result; // And then assign it to the actual parameter after calling the delegate.
return result;
}
Calling the function does then work like this:
public bool CanUpdateUser(string userName, out string errorMessage)
{
bool result = SafetyExecuteFunctionWithOut<string, string, bool>(_innerSession.CanUpdateUser, userName, out errorMessage);
return result;
}
Note, that you have to pass _innerSession.CanUpdateUser as a parameter to SafetyExecuteFunctionWithOut instead of using a lambda expression.
Using the naive attempt:
private TResult SafetyExecuteFunctionWithOut<T1, T2, TResult>(FuncWithOut<T1, T2, TResult> func, T1 arg1, out T2 arg2)
{
TResult result = default(TResult);
SafetyExecuteMethod(() => result = func(arg1, out arg2));
return result;
}
creates the error message:
CS1628 Cannot use ref or out parameter 'arg2' inside an anonymous
method, lambda expression, or query expression
Why you are not allowed to do that is explained in this answer.
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
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.
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);
};
}
I am using an external automation library with bunch of APIs with either 1 or 2 parameters which randomly throws TargetInvocationException. Calling these APIs second or third time usually works. I therefore created two helper methods to encapsulate the multiple retry logic
//Original API calls
bool result1 = Foo1(true);
int result2 = Foo2(4, "abc");
//New API calls
bool result1 = SafeMethodCall(Foo1, true);
int result2 = SafeMethodCall(Foo2, 4, "abc");
//Helper Methods
public static TResult SafeMethodCall<T, TResult>(
Func<T, TResult> unSafeMethod,
T parameter)
{
int numberOfMethodInvocationAttempts = 3;
int sleepIntervalBetweenMethodInvocations = 10000;
for (int i = 0; i < numberOfMethodInvocationAttempts; i++)
{
try
{
return unSafeMethod(parameter);
}
catch (System.Reflection.TargetInvocationException ex)
{
System.Threading.Thread.Sleep(sleepIntervalBetweenMethodInvocations);
}
}
}
public static TResult SafeTargetInvocationMethodCall<T1, T2, TResult>(
Func<T1, T2, TResult> unSafeMethod,
T1 parameter1,
T2 parameter2)
{
int numberOfMethodInvocationAttempts = 3;
int sleepIntervalBetweenMethodInvocations = 10000;
for (int i = 0; i < numberOfMethodInvocationAttempts; i++)
{
try
{
return unSafeMethod(parameter1, parameter2);
}
catch (System.Reflection.TargetInvocationException ex)
{
System.Threading.Thread.Sleep(sleepIntervalBetweenMethodInvocations);
}
}
}
Problem: If you see the two helper methods above have the same body and the only difference is unsafeMethod call inside the try block. How can I avoid code duplication here as I might have to add a overloaded method that accepts
Func<TResult>
as another parameter type.
Just pass in Func<TResult> and call it like this:
bool result1 = SafeMethodCall(() => Foo1(true));
int result2 = SafeMethodCall(() => Foo2(4, "abc"));
In other words, encapsulate the arguments in the delegate itself.