❔ asynchronous coding

Hello, nice coding. I have a synchronous packet filter project that I coded myself and I updated my project to .net 6.0 and I want to update it asynchronously. Ex: public async Task<PacketResult> Handle(Session session, Packet packet) { if (Settings.ConnectionLimit> 0) { var count = SqlHelper.Count(session.Context.CharName); if (count >= Settings.ConnectionLimit) { session.SendNotice(NoticeClass.Limit); return PacketResult.Ignore; } } return PacketResult.None; } You have many asynchronous methods similar to the above code and they don't have await or task run statements any problem? thank you for your feedback
23 Replies
V0FBU1VM
V0FBU1VM17mo ago
Is this your own method?
『LoG』☠  𝓣 𝓐 𝓛 𝓔 𝓝 𝓣  ♚
Yea? Sorry, I'm not very good at asynchronous coding.
V0FBU1VM
V0FBU1VM17mo ago
It's fine mate, no problem. If you are in need of running the operation asynchronously then use the async modifier other wise you don't have too.
jcotton42
jcotton4217mo ago
there's no point to the async or Task<T> return type here since the body is sync there's no reason at all to use async here and you should only use the Task<T> return if you're having to fulfill an interface that needs that reutrn type in which case, use Task.FromResult(foo) to create the task to return
『LoG』☠  𝓣 𝓐 𝓛 𝓔 𝓝 𝓣  ♚
public Task<PacketResult> Handle(Session session, Packet packet) { if (Settings.ConnectionLimit) { session.SendNotice(NoticeClass.ConnectionLimit); return Task.FromResult(PacketResult.Ignore); } return Task.FromResult(PacketResult.None); } One of the methods I use is as follows I preferred this method because more than one packet is sent for a user and many packets usually contain some blocking.
jcotton42
jcotton4217mo ago
what does session.SendNotice do?
『LoG』☠  𝓣 𝓐 𝓛 𝓔 𝓝 𝓣  ♚
public void SendNotice(string notice, bool useAsync = true) { Packet packet = new Packet(0x300C); packet.WriteValue<ushort>(3100); packet.WriteValue<byte>(1); packet.WriteValue<string>(notice); ClientSecurity.Send(packet); packet = new Packet(0x300C); packet.WriteValue<ushort>(3100); packet.WriteValue<byte>(2); packet.WriteValue<string>(notice); ClientSecurity.Send(packet); if (useAsync) { TransferToClientAsync(); } else { TransferToClient(); } } the method i use to send messages to clients
jcotton42
jcotton4217mo ago
and TransferToClientAsync? if that's an actual Task-returning method, that's... not great since you're not awaiting it
『LoG』☠  𝓣 𝓐 𝓛 𝓔 𝓝 𝓣  ♚
public virtual void TransferToClientAsync() { try { var transferBuffers = ClientSecurity.TransferOutgoing(); if (transferBuffers == null) return; foreach (var (transferBuffer, _) in transferBuffers) { SendAsync(transferBuffer.Buffer, transferBuffer.Offset, transferBuffer.Size); } } catch (Exception) { Disconnect(); } } i am trying to convert this project from .net framework to .net 6.0
V0FBU1VM
V0FBU1VM17mo ago
That method is not asynchronous.
『LoG』☠  𝓣 𝓐 𝓛 𝓔 𝓝 𝓣  ♚
public virtual bool SendAsync(byte[] buffer, int offset, int size) { if (!IsConnected) return false; if (size == 0) return true; lock (_sendLock) { // Fill the main send buffer _sendBufferMain.Append(buffer, offset, size); // Avoid multiple send handlers if (_sending) return true; _sending = true; // Try to send the main buffer Task.Factory.StartNew(TrySend); } return true; } i said i'm bad at asynchronous coding, i'm just at the beginning unfortunately,
Omnissiah
Omnissiah17mo ago
do you need a lock there? also send is calling trysend? i mean...
『LoG』☠  𝓣 𝓐 𝓛 𝓔 𝓝 𝓣  ♚
private void TrySend() { if (!IsConnected) return; bool isProcess = true; while (isProcess) { isProcess = false; lock (_sendLock) { // Is previous socket send in progress? if (_sendBufferFlush.IsEmpty) { // Swap flush and main buffers _sendBufferFlush = Interlocked.Exchange(ref _sendBufferMain, _sendBufferFlush); _sendBufferFlushOffset = 0; // Check if the flush buffer is empty if (_sendBufferFlush.IsEmpty) { // End sending process _sending = false; return; } } else return; } try { // Async write with the write handler _sendEventArg.SetBuffer(_sendBufferFlush.Data, _sendBufferFlushOffset, _sendBufferFlush.Size - _sendBufferFlushOffset); if (!Socket.SendAsync(_sendEventArg)) isProcess = ProcessSend(_sendEventArg); } catch (ObjectDisposedException obj) { Console.WriteLine(obj); } } }
jcotton42
jcotton4217mo ago
yeah, that's not properly async at all the whole chain should be Task-returning and awaited
『LoG』☠  𝓣 𝓐 𝓛 𝓔 𝓝 𝓣  ♚
yes i need a lockthere
V0FBU1VM
V0FBU1VM17mo ago
Ok, all of the methods you have provided are actually synchronous methods. Here is the difference
In synchronous operations, tasks are executed one after the other, in a sequential order. Each task has to wait for the previous one to complete before it can start. When a synchronous function or process is called, the program will wait for that function to finish executing before moving on to the next line of code. This can lead to blocking behavior, where the entire program has to wait for slow operations to complete before it can proceed, potentially causing performance issues and delays.
In synchronous operations, tasks are executed one after the other, in a sequential order. Each task has to wait for the previous one to complete before it can start. When a synchronous function or process is called, the program will wait for that function to finish executing before moving on to the next line of code. This can lead to blocking behavior, where the entire program has to wait for slow operations to complete before it can proceed, potentially causing performance issues and delays.
In asynchronous operations, tasks are executed independently of one another. When an asynchronous function or process is called, it doesn't block the program's execution; instead, it allows the program to continue running while the task is being processed. As a result, multiple tasks can run concurrently, and the program can be more efficient when dealing with time-consuming operations, such as I/O operations or network requests.
In asynchronous operations, tasks are executed independently of one another. When an asynchronous function or process is called, it doesn't block the program's execution; instead, it allows the program to continue running while the task is being processed. As a result, multiple tasks can run concurrently, and the program can be more efficient when dealing with time-consuming operations, such as I/O operations or network requests.
Omnissiah
Omnissiah17mo ago
also probably using pastebin would be better if there is so much code
jcotton42
jcotton4217mo ago
yeah, use $paste in the future for that much code
MODiX
MODiX17mo ago
If your code is too long, you can post to https://paste.mod.gg/ and copy the link into chat for others to see your shared code!
『LoG』☠  𝓣 𝓐 𝓛 𝓔 𝓝 𝓣  ♚
yes my code is from a pretty big project and I'm afraid I can't upload all the code
V0FBU1VM
V0FBU1VM17mo ago
@ǃ I would recommend taking a look at this tutorial on C#Async/Await https://www.youtube.com/watch?v=2moh18sh5p4&ab_channel=IAmTimCorey
IAmTimCorey
YouTube
C# Async / Await - Make your app more responsive and faster with as...
Asynchronous programming can be intimidating. What is even worse is when you think you learned how to do something and then you try it in your application, and it doesn't work. This video is an attempt to fix all of that. In it, you will see how to use the async and await keywords to make your user interface more responsive and to speed up your ...
『LoG』☠  𝓣 𝓐 𝓛 𝓔 𝓝 𝓣  ♚
Thank you everyone for your nice informative posts.❤️
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server