异步并等待TCP Socket C#.Net 4.6 [英] async and await in TCP Socket C# .Net 4.6

查看:82
本文介绍了异步并等待TCP Socket C#.Net 4.6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在重写.net 4.6中的Socket库,以获得现有的最新功能和性能改进申请。 

我的申请与股票市场交易有关。所以性能和可能的极低延迟是至关重要的。



我在基于c#5的Async套接字的Google搜索中经历了很多线程,但无法找到完整的流程,我可以用来实现我的套接字。



这是我用来实现新库的一个例子。



https://stackoverflow.com/a/12631467



在这个帖子里,我被困在"EchoAsync"中。函数,其中处理从客户端套接字接收的数据



 var amountRead = amountReadTask.Result; 
if(amountRead == 0)break; // end.await的结尾
stream.WriteAsync(buf,0,amountRead,ct).ConfigureAwait(false);



因为我的代码是抽象库。我正在根据"amountread"从接收的数据创建byte []缓冲区。现在我想在我现有的覆盖方法中使用这个byte [],我正在处理基于API协议的缓冲区数据。



我的新代码看起来像这样

  byte [] tempBuffer = new byte [amountRead];  
Buffer.BlockCopy(buf,0,tempBuffer,0,amountRead); 
await OnDataArrival(tempBuffer).ConfigureAwait(false);

现在问题是我不知道如何实现"OnDataArrival" as async方法,这是我现有代码中的常规方法。基于一些谷歌搜索我尝试实现这样的代码,但我不知道这将如何响应低延迟
和高性能,因为我的承诺是创建一个任务耗时并创建高延迟,除非它很费时间。我的数据到达功能要求是过程数据尽可能快,并且响应数据到客户端系统另一个
tcp。

公共覆盖任务OnDataArrival(byte []数据)
{
尝试
{
而(data.Length> 2)
{
//处理数据
}
}
catch(exception ex)
{
WriteTrace(ex.Message);
}
返回Task.CompletedTask;
}


我已经完成了很多线程,但无法理解如何实现这一目标。任何带代码块的指南都会有很大的帮助。


谢谢,






Jiten Patoliya Windows C#developer

解决方案

这完全取决于流程数据评论。通常,您可以通过将代码包装在Task.Run中来将通常同步的代码转换为异步。

 

public override Task OnDataArrival(byte [] data)
{
return Task.Run(()= >
{
尝试
{
while(data.Length> 2)
{
};
} catch(Exception ex )
{
WriteTrace(ex.Message);
};
});

}


请注意,将sync方法转换为异步并使用try-catch逻辑可以更改错误的处理方式。确保在您希望的线程上处理try-catch。使用共享数据时也要非常小心。最终任务
代码在不同的线程上运行,因此需要考虑线程安全性及其周围的所有常见问题。 


<但这是一个开始。您应该分离过程数据代码,并将每个花费任何时间的调用转换为异步调用。完成后,您可以完全删除Task.Run。这将允许更好的取消支持,将
的非异步和异步代码编织在一起,并使代码更易于维护。

 //应该是OnDataArrivalAsync并且应该支持CancellationToken 
公共覆盖异步任务OnDataArrival(byte []数据)
{
//这个try-catch在异步代码之外所以它将
//可能得到聚合异常
尝试
{
while(data.Length> 2)
{
await DoSomeAsyncWork()。ConfigureAwait(false);

//这是同步代码,但会在其他一些线程上运行
DoMoreWorkSync();

等待DoSomeMoreAsyncWork()。ConfigureAwait(false);
};
} catch(Exception ex)
{
await WriteTraceAsync(ex);
};
}

Michael Taylor


http: //wwww.michaeltaylorp3.net




Hi,

I am rewriting my Socket library in .net 4.6 for benefit of latest feature and performance improvement in existing application. 
My application is related to stock market trading. So Performance and possible extreme low latency is crucial in that.

I am going through lot of threads in Google search based on Async sockets on c# 5, but unable to find complete flow, which i can use to implement my socket.

Here's one of example I am using to implement new library.

https://stackoverflow.com/a/12631467

In this thread I am stuck at "EchoAsync" function, where received data from client socket is processed

var amountRead = amountReadTask.Result;
if (amountRead == 0) break; //end of stream.await 
stream.WriteAsync(buf, 0, amountRead, ct).ConfigureAwait(false);


As my code is abstract library. I am creating byte[] buffer from the received data based on "amountread". Now I want  to use this byte[] in my existing overriden method where I am processing buffer data based on API protocol.

My new code look like this

 byte[] tempBuffer = new byte[amountRead]; 
Buffer.BlockCopy(buf, 0, tempBuffer, 0, amountRead); 
await OnDataArrival(tempBuffer).ConfigureAwait(false);  

Now problem is I don't know how can i implement "OnDataArrival" as async method, which is normal method in my existing code. Based on some googling i try to implement code like this, But I am not sure how this would respond in terms of low latency and high performance, as my undertanding is creating a Tasks are time consuming and create high latency unless it is time consuming. My dataarrival function requirement is process data as fast fast possible and response that data to client system on another tcp.

public override Task OnDataArrival(byte[] data)
{
	try
	{
		while (data.Length > 2)
		{
			//Process data
		}
	}
	catch (Exception ex)
	{
		WriteTrace(ex.Message);
	}
	return Task.CompletedTask;
}

I have gone through lot of threads but unable to understand how to achieve this. Any guide with code block would be great help.

Thanks,


Jiten Patoliya Windows C# developer

解决方案

It completely depends upon that process data comment. In general you can convert code that is normally sync to async by wrapping it in a Task.Run.

public override Task OnDataArrival ( byte[] data ) { return Task.Run(() => { try { while (data.Length > 2) { }; } catch (Exception ex) { WriteTrace(ex.Message); }; });

}

Note that converting a sync method to async with try-catch logic in it can change how the errors are handled. Ensure that your try-catch is handled on the thread that you want it to. Also be very careful about using data that is shared. Ultimately the task code runs on a different thread so thread safety and all the common issues around it need to be considered. 

But this is a start. You should pick apart the process data code and convert each call that takes any amount of time to an async call. Once you've done that you can remove the Task.Run altogether. This will allow for better cancellation support, weaving of non-async and async code together and makes for more maintainable code.

//Should really be OnDataArrivalAsync and should support CancellationToken
public override async Task OnDataArrival ( byte[] data )
{
   //This try-catch is outside the async code so it will 
   //potentially get aggregate exceptions
   try
   {
      while (data.Length > 2)
      {
          await DoSomeAsyncWork().ConfigureAwait(false);

          //This is sync code but will run on some other thread
          DoMoreWorkSync();
 
          await DoSomeMoreAsyncWork().ConfigureAwait(false);    
      };
   } catch (Exception ex)
   { 
       await WriteTraceAsync(ex);
   };
}

Michael Taylor

http://wwww.michaeltaylorp3.net


这篇关于异步并等待TCP Socket C#.Net 4.6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆