我有一份股票清单,我想浏览清单并获取每只股票的价格,我想要它,因为该程序不占用大量CPU,因此我需要它在一分钟内获得所有价格还会在处理过程中保存到文本文件
我正在使用的api将允许我每分钟建立1万个连接,因此DDos不会成为问题
我将在其上运行该程序的PC只有一个CPU,所以我不认为多线程不是一种选择
到目前为止,这是我创建的代码
它在我的多核计算机上可以正常工作,但仍然不够快,但在单核计算机上却不能很好
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(Threads);
t.Start();
}
private object acctLock = new object();
static readonly object syncRoot = new object();
private void Threads()
{
string filePathAccounts = "";
if (radioButtonCarrierAccountsFile.Checked)
{
filePathAccounts = textBoxAccountsCarrier.Text;
}
List<string> stockList = File.ReadAllLines(filePathAccounts).ToList();
int accountPosition = 0;
int totalAccounts = stockList.Count;
Parallel.ForEach(stockList.AsParallel(), new ParallelOptions { MaxDegreeOfParallelism = Convert.ToInt32(textBoxThreads.Text) }, recipient =>
{
lock (acctLock)
{
string[] stockEntries = stockList[accountPosition].Split(',');
// This creates an array so we can add each line to its own variable
stock = stockList[Convert.ToInt32(0)];
++accountPosition;
}
// connecto to api and get info
string stockPrice = "Price received from api json";
lock (acctLock)
{
StreamWriter appendToFile = new StreamWriter("stockPrice.txt", true);
appendToFile.WriteLine($"{stock},{stockPrice}");
appendToFile.Dispose();
}
});
}