❔ 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
Is this your own method?
Yea?
Sorry, I'm not very good at asynchronous coding.
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.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 returnpublic 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.
what does session.SendNotice do?
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
and TransferToClientAsync?
if that's an actual Task-returning method, that's... not great
since you're not awaiting it
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
That method is not asynchronous.
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,
do you need a lock there?
also send is calling trysend? i mean...
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);
}
}
}
yeah, that's not properly async at all
the whole chain should be Task-returning and awaited
yes i need a lockthere
Ok, all of the methods you have provided are actually synchronous methods. Here is the difference
also probably using pastebin would be better if there is so much code
yeah, use $paste in the future for that much code
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!
yes my code is from a pretty big project and I'm afraid I can't upload all the code
@ǃ 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 ...
Thank you everyone for your nice informative posts.❤️
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.