简体   繁体   English

多线程环境中的C#/ SQLServer数据库连接

[英]C#/SQLServer Database Connections in multithreaded environment

I have a multithreaded application.Each thread will be responsible for uploading data to a SQL Database.My question is that, what is the correct solution to do this? 我有一个多线程应用程序,每个线程将负责将数据上传到SQL数据库。我的问题是,这样做的正确解决方案是什么? Each thread shall open its own new db connection or some singleton pattern shall be used for creating database. 每个线程应打开自己的新数据库连接,或使用某些单例模式来创建数据库。 Or please let me know if there is any other best approach for this. 或者,如果有其他最佳方法,请告诉我。 Any code sample will be highly appreciated. 任何代码示例都将受到高度赞赏。

You don't have to open multiple connections to call your WCF service multiple times at once. 您无需打开多个连接即可一次调用WCF服务。 All you have to do is to use an asynchronous way to call it. 您要做的就是使用异步方式来调用它。 You can for example use Parrallel.ForEach() instead of creating your own threads. 例如,您可以使用Parrallel.ForEach()而不是创建自己的线程。

public void UploadData(List<Data> allDataToUpload)
{
    Parallel.ForEach(allDataToUpload, data =>
    {
        _yourService.Upload(data);
    });
}

Also, if you are not VERY familiar with threading, I suggest to use all the new tools provided by Microsoft since .net 4.5 like async, await and the library Task instead of managing your own threads. 另外,如果您不太熟悉线程,建议您使用Microsoft提供的.net 4.5以后的所有新工具(例如async,await和库Task),而不要管理自己的线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM