C# Sockets ReceiveAsync No overload for method error - c#

I am creating a Chatting application in a C# console app and just starting to learn about async tasks rather than just multi-threading which from my understanding is sort of outdated and better off using async.
I am using Microsoft's official documentation on sockets as a sort of guide to my own application because they use asynchronous programming but am getting an error.
Here is the code where I get the error:
private async Task handleClientsAsync(Socket server)
{
Byte[] _buffer = new Byte[1024];
Socket client = await server.AcceptAsync();
while (true)
{
bool received = await client.ReceiveAsync(_buffer, SocketFlags.None); //This is the line with the error
}
}
The error is: "No overload for method 'ReceiveAsync' takes '2' arguments." This confuses me because, on Microsoft's official documentation, they pass through the same parameters.
Any help is much appreciated :)

The error is a bit misleading. While there are no overloads that take 2 arguments, there are extension methods that do.
Some of the overloads for ReceiveAsync() were moved to extension methods between .NET 4.7 and .NET 4.7.1, in the System.Net.Sockets.SocketTaskExtensions class. As long as you have using System.Net.Sockets; at the top of your file, you can use those extension methods.
So why doesn't it work? Well, there never was an overload that accepted a plain byte array. But there was an overload that accepted Memory<Byte> and the Memory<T> class has an operator to implicitly cast.
That version of the overload was not moved to the extension methods. The only equivalent one accepts ArraySegment<Byte>, and ArraySegment<T> has no implicit casting operator. So you have to create the ArraySegment<Byte> yourself.
Although, even after you fix that, you'll get a compiler error warning that you can't implicitly cast an int to bool, since ReceiveAsync() has always returned an int.
You can change that line to this:
var received = await client.ReceiveAsync(new ArraySegment<byte>(_buffer), SocketFlags.None); //This is the line with the error
The ArraySegment<T> struct does not copy the underlying array. It's just a way to refer to a section of an array. If you do not pass a range to the constructor, then it refers to the whole array.

Related

Delegate does not contain a definition for 'CreateDelegate'

Using Unity 2018-2017 with same problem on building for net-
error CS0117: 'Delegate' does not contain a definition for 'CreateDelegate'
This is the method:
private V CreateDelegate<V>(MethodInfo method, Object target) where V : class
{
var ret = (Delegate.CreateDelegate(typeof(V), target, method) as V);
if (ret == null)
{
throw new ArgumentException("Unabled to create delegate for method called " + method.Name);
}
return ret;
}
Building for UWP.
Using system.Linq
I tryed with "MethodInfo" but maybe some parameters are wrong.
This method isn´t available?
Which platform/runtime are you targeting? I don't know about Mono, but .Net standard 1.x doesn't support Delegate.CreateDelegate. Always keep in mind that you're writing your code against a limited subset of the .Net framework. Also keep in mind that your code will inevitably be AOT-compiled on some platforms (il2cpp, iOS, etc.), so some reflection/emit features will be unavailable.
Note: AOT means ahead-of-time, meaning your code is compiled to machine instructions rather than an intermediate language. Reflection is when you use the code itself as data, so for example you can get a list of the properties a class defines. Emit means generating code at runtime. If you don't understand what those are, you should probably do some studying. It's well worth the effort in the long run.
1. Your return type is a class, not a delegate.
where V : class
So this method doesn't even make sense. You're going to get an invalid cast exception.
2. CreateDelegate takes 2 parameters, not 3.
I'm not even sure what purpose target even serves here, so I can't even guess what you're trying to do.

Speeding up calls on MethodInfo

I have implemented a compiler and virtual machine for a language. The implementation is in C# and the stack-based VM uses reflection to make function calls on a set of built-ins.
Much of the code involves simply pushing and popping stack values, but the workhorse is the function call. Currently the implementation of a function call looks like this:
var calli = gencode[pc++] as CallInfo;
var calla = PopStackList(calli.NumArgs).ToArray();
var ret = calli.MethodInfo.Invoke(instance, calla);
if (ret != null) PushStack(ret);
All data items passed and returned are objects using a custom type system (no native types used). Clarification: this is an instance method, not static.
Performance testing suggests that this MethodInfo.Invoke is quite slow. The question is how to make function calls at the highest possible speed, presumably by doing more preparatory work in the compiler and generating better code.
In response to suggestions, one possibility is to create a delegate. Unfortunately as far as I can tell a delegate has to be bound to a specific instance of a class, or to a static method, and creating a delegate after creating the instance rather defeats the purpose.
I see a vote to close, but to my eye the question is not broad at all. How should a compiler implement functions calls on instance methods in a virtual machine for best performance, at the very least faster than MethodInfo.Invoke()?
Well, if you’re sure your main problem is MethodInfo.Invoke…
Use stuff from System.Linq.Expressions (Expression.Call, Expression.Parameter) to create an expression that calls that MethodInfo method, passing your parameters for instance + arguments.
Compile that expression into Action<tInstance, tArgs[]> (don't know your types of these).
Cache that Action in your CallInfo class instance.
Invoke that action as needed.
How to convert MethodInfo.Invoke to delegate:
Normally when you’re calling methods with reflection, you call MethodInfo.Invoke. Unfortunately, this proves to be quite slow. If you know the signature of the method at compile-time, you can convert the method into a delegate with that signature using Delegate.CreateDelegate(Type, object, MethodInfo). You simply pass in the delegate type you want to create an instance of, the target of the call (i.e. what the method will be called on), and the method you want to call. It would be nice if there were a generic version of this call to avoid casting the result, but never mind. Here’s a complete example demonstrating how it works:
using System;
using System.Reflection;
public class Test
{
static void Main()
{
MethodInfo method = (string).GetMethod(“IndexOf”, new Type[]{typeof(char)});
Func<char, int> converted = (Func<char, int>)
Delegate.CreateDelegate(typeof(Func<char, int>), “Hello”, method);
Console.WriteLine(converted(‘l’));
Console.WriteLine(converted(‘o’));
Console.WriteLine(converted(‘x’));
}
}
This prints out 2, 4, and -1; exactly what we’d get if we’d called "Hello".IndexOf(...) directly. Now let’s see what the speed differences are…
We’re mostly interested in the time taken to go from the main calling code to the method being called, whether that’s with a direct method call, MethodInfo.Invoke or the delegate. To make IndexOf itself take as little time as possible, I tested it by passing in ‘H’ so it would return 0 immediately. As normal, the test was rough and ready, but here are the results:
Invocation type Stopwatch ticks per invocation
Direct 0.18
Reflection 120
Delegate 0.20
Copied from: https://blogs.msmvps.com/jonskeet/2008/08/09/making-reflection-fly-and-exploring-delegates/

How to read/interpret a raw C# stack trace correctly?

I'm reading some crash reports from a UWP application (C#, compiled with .NET Native) and I'm having a hard time understanding the exact syntax/format used in the stack traces.
I tried looking for some guides on the internet but I didn't come up with anything useful.
Here are a few examples:
1)
MyProject.ViewModels.SomeViewModel.<OnLogin>d__69.MoveNext()
OnLogin is the name of a method in SomeViewModel, so why is it inside angular brackets? Is the "ClassName".<"MethodName>..." the usual way to indicate an instance method?
I understand that the C# compiler turns every chunk of code between await calls into anonymous methods and schedules them using continuations, so I guess that d__69 indicates an async continuation inside the current method.
What does the 'd' stand for?
Are those numbers random? I mean, the method doesn't have 69 await calls, so I guess those numbers aren't sequential. Is it possible to find out the exact part in the original method from that number in the stack trace?
What is that MoveNext() method at the end? What kind of type is it called upon?
2)
MyProject.UserControls.SomeControl.<.ctor>b__0_0
I know that .ctor stands for the object constructor, and looking at the code I found out that b__0_0 stands for an anonymous event handler added inside the constructor, like this: SomeEvent += (s, e) => Foo();.
What does the 'b' stand for?
Why are there two numbers with an underscore? Which one of them refers to the anonymous method index? I mean, it's the first one (so its index is 0) but there are two 0s here. If it was the second, would I have had 0_1, 1_0 or something else?
3) I have this method:
// Returns a Task that immediately throws when awaited, as soon as the token is cancelled
public static Task<T> GetWatchedTask<T>(this Task<T> awaitableTask, CancellationToken token)
{
return awaitableTask.ContinueWith(task => task.GetAwaiter().GetResult(), token);
}
And I have this stack trace:
MyProject.Helpers.Extensions.TasksExtensions.<>c__3$1<System.__Canon>.<GetWatchedTask>b__3_0($Task$1<__Canon> task)
Why doesn't the second parameter (the token) show up in the signature?
Why is the type $Task$1 written with the '$' character? Is it like some sort of placeholder/ground indicator (like in a regex) so that it can be used in other places too? (I mean, I see that $1<System.__Canon> in what I guess is the method return type)
If that first part is the method return type, why isn't it there for all the methods that have a return type? I have lots of stack traces with method that do return a value, but they don't have that same signature.
What does all that .<>c__3$1<System.__Canon> mean? From the $1 and on I guess that'd be the Task<T> return type, but what's that b__3_0 part, since I don't have async calls or event handlers? Does that mean something different in this case?
4)
Windows.UI.Xaml.Media.SolidColorBrush..ctor($Color color)
Why does the parameter type start with the '$' character? What does it stand for?
5) I have this other method:
public static async Task<ObservableCollection<SomeCustomClass>> LoadItemGroups(String parentId)
And this stack trace:
MyProject.SQLiteDatabase.SQLiteManager.<>c__DisplayClass142_3.<LoadGroups>b__3()
What's that c__DisplayClass142_3? Is that a way to indicate the return type with a single type rather than the three separate classes (Task, ObservableCollection, SomeCustomClass)?
Again, why do I have b__3 here, where in other stack traces it used the format d_xxx to indicate an async code chunk?
Sorry for the many questions, I hope this post will help other UWP C# programmers too.
Thank you in advance for your help!
EDIT: this question should not be considered a duplicate of this other questions because:
It presents different cases (constructor methods, generic types syntax etc..) instead of just asking for the meaning of some default keywords/symbols related to a certain type of variables
It specifically asks how to compare a given stack trace to an original method signature, and the steps to do in order to achieve that
It presents different examples in different contexts, instead of just asking a general question
And by the way, how can "VS debugger magic names" even be considered a proper question title? How was another user supposed to find that question when looking for C# stack traces symbols meaning?
I bet Eric Lippert will come later and give a better answer, but in case that won't happen - here is my take, because I also got interested in this. The meaning of "d", "c" and similar symbols I got from this answer by Eric Lippert.
1) MyProject.ViewModels.SomeViewModel.<OnLogin>d__69.MoveNext()
This one is relatively simple. OnLogin is async method, and such methods are rewritten by compiler into a state machine. This state machine implements IAsyncStateMachine interface which has MoveNext method. So your async method basically becomes a sequence of MoveNext invocations of that state machine. That is why you see MoveNext() in stack trace.
MyProject.ViewModels.SomeViewModel.<OnLogin>d__69 is the name of generated state machine class. Because this state machine is related to OnLogin method - it becomes part of type name. d is "iterator class" by the link above. Note that information from link above is 7 years old and is before async\await implementation, but I guess that state machine is similar to iterator (the same MoveNext method, same principle) - so "iterator class" looks fine. 69 is some unique number \ counter. I guess it's just counter, because if I compile dll with just two async methods - their state machines would be d__0 and d__1. It's not possible to deduce which part of async method has thrown based on this info.
2) b is "anonymous method" (link above). I made some experiments and I think first index is related to the method in which anonymous method was used, and second index seems to be related to index of anonymous method inside that method in which they are used. For example suppose you use 2 anonymous methods in constructor and 2 anonymous methods in method Foo in the same class. Then:
public Test() {
Handler += (s, e) => Foo(); // this will be `b__0_0` because it's first in this method
Handler += (s, e) => Bar(); // this will be `b__0_1` because it's second
}
static void Foo() {
Action a = () => Console.WriteLine("test"); // this is `b__1_0`, 1 refers to it being in another method, not in constructor.
// if we use anonymous method in `Bar()` - it will have this index 2
a();
Action b = () => Console.WriteLine("test2"); // this is `b__1_1`
b();
}
3) This looks quite complicated. First you ask "Why doesn't the second parameter (the token) show up in the signature". That's simple - because method in question represents anonymous method task => task.GetAwaiter().GetResult(), not your GetWatchedTask method. Now I was not able to reproduce your stack trace with this one, but still some info. First, System.__Canon is:
Internal methodtable used to instantiate the "canonical"
methodtable for generic instantiations.
The name "__Canon" will never been seen by users but it will appear a lot in debugger stack traces
involving generics so it is kept deliberately short as to avoid being a nuisance.
Looks cryptic for me, but I guess it kind of represents your T in runtime. Then, <>c__3$1<System.__Canon> is <>c__3$1<T> and is a name of compiler generated class, where "c" is "anonymous method closure class" (from the link above). Such class is generated by compiler when you create a closure, so capture some external state in your anonymous method. What has been captured should be stored somewhere, and it is stored in such class.
Going futher, <GetWatchedTask>b__3_0 is a method in that anonymous class above. It represents your task => task.GetAwaiter().GetResult() method. Everything from point 2 applies here as well.
I don't know the meaning of $, maybe it represents number of type parameters. So maybe Task$1<System.__Canon> means Task<T> and something like Tuple$2<System.__Canon would mean Tuple<T1, T2>.
4) That I unfortunately don't know and was not able to reproduce.
5) c__DisplayClass142_3 is again closure class (see point 3). <LoadGroups>b__3() is anonymous method you used in method LoadGroups. So that indicates some anonymous method which is closure (captured external state) and which was called in LoadGroups method.

How to convert from UICollectionElementKindSection.Header to NSString?

I'm using Xamarin.iOS. How can I convert UICollectionElementKindSection.Header to NSString?
Error CS1503: Argument #1' cannot convertUIKit.UICollectionElementKindSection' expression to type `Foundation.NSString' (CS1503)
I tried the following:
UICollectionElementKindSection.Header.ToString();
(NSString)UICollectionElementKindSection.Header;
(string)UICollectionElementKindSection.Header;
Everytime I get a build error.
For type-safety UICollectionElementKindSectionHeader (and other values) are mapped to an enum, UICollectionElementKindSectionKey. That makes code completion a lot easier (in the IDE) and remove potential typos/mistakes in code.
Turning the enum values into a string (and then an NSString) is possible - but that won't create the same NSString constant that ObjC applications used (even less since, sometime, Apple uses pointers, not string content, for constant comparison).
If you need to use an API that does not use the enum but needs that constant you can do:
IntPtr uikit = Dlfcn.dlopen (Constants.UIKitLibrary, 0);
NSString header = Dlfcn.GetStringConstant (uikit, "UICollectionElementKindSectionHeader");
Note: if that's an API part of Xamarin.iOS.dll then please let us know. We'll either expose the constant or provide an overload that accept the enum.
(NSString)UICollectionElementKindSection.Header.ToString() throws no build error anymore. My app still doesn't work but it's for another reason.

C# new [delegate] not necessary?

I've been playing with HttpWebRequests lately, and in the tutorials they always do:
IAsyncResult result = request.BeginGetResponse(
new AsyncCallback(UpdateItem),state);
But new AsyncCallback doesn't seem to be necesary. If UpdateItem has the right signature, then there doesn't seem to be a problem. So why do people include it? Does it do anything at all?
It's the same thing, mostly (there are a few overload rules to think about, although not in this simple example). But in previous versions of C#, there wasn't any delegate type inference. So the tutorial was either (a) written before delegate type inference was available, or (b) they wanted to be verbose for explanation purposes.
Here's a summary of a few of the different ways you can take advantage of delegate type inferencing:
// Old-school style.
Chef(new CookingInstructions(MakeThreeCourseMeal));
// Explicitly make an anonymous delegate.
Chef(delegate { MakeThreeCourseMeal });
// Implicitly make an anonymous delegate.
Chef(MakeThreeCourseMeal);
// Lambda.
Chef(() => MakeThreeCourseMeal());
// Lambda with explicit block.
Chef(() => { AssembleIngredients(); MakeThreeCourseMeal(); AnnounceDinnerServed(); });
AsyncCallback is just a delegate in C#, it is declared as
public delegate void AsyncCallback(IAsyncResult ar);
When you pass the method name itself as long as the signature matches the compiler will usually substitute the code for you, its just shortcut.
You can simply check this using Reflector. If you have this for example.
request.BeginGetResponse(TestMethod, null);
static void (IAsyncResult r)
{
//do something
}
The compiled code will actually look like this.
request.BeginGetResponse(new AsyncCallback(Test), null);
For completeness, this changes between C# 1.2 (with .NET 1.1) and C# 2.0 (with .NET 2.0). So from 2.0 onwards you can indeed omit the new SomeDelegateType(...) in most scenarios. Oddly, the tooling hasn't changed, so in the IDE if you type someObj.SomeEvent += the IDE will suggest (via tab tab) the full version including delegate type.

Categories

Resources