gpt4 book ai didi

mysql - 为什么我的辅助角色在 Azure 上使用了高达 99% 的 CPU?

转载 作者:行者123 更新时间:2023-11-30 22:58:38 27 4
gpt4 key购买 nike

我一直在本地调试该角色,它占用了高达 9% 的 CPU,但是当我将其上传到临时实例时,它占用了高达 99.37% 的 CPU 使用率。

我的角色是一个多线程 TCP 服务器,在某个端口监听数据插入,它处理数据并将其插入到与该角色位于同一区域的 MySQL 数据库中。

服务器一旦开始运行就会在线程中启动。

这是我的 Run 方法的代码...

public override void Run()
{
Trace.TraceInformation("Data Collector initialized!");
Server tcpServer = new Server();
tcpServer.Start();
while (true)
{

}
}

这是我用来处理所有数据的服务器类。服务器为每个接受的套接字创建一个线程,我目前只使用一台设备,每 15 分钟发送一次数据...

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using Microsoft.WindowsAzure.ServiceRuntime;
using MySql.Data.MySqlClient;

namespace Data_Collector
{
public class Server
{
public TcpListener listener; //Listens fot TCP connections
//Port that the server will be listening.
private int Port;
private Thread listenerThread;
private IPAddress Ip;
private MySqlConnection databaseConnection;
private string server = "x.x.x.x";
private string database = "database";
private string uid = "user";
private string password = @"password";
private string connectionString;

/// <summary>
/// Initialize the server with the service IP and Endpoint.
/// </summary>
public Server()
{
Port = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Data"].IPEndpoint.Port;
Ip = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["Data"].IPEndpoint.Address;
}
/// <summary>
/// Starts the server.
/// </summary>
public void Start()
{
listener = new TcpListener(Ip, Port);
listener.Start();
listenerThread = new Thread(new ThreadStart(Listen));
listenerThread.Start();
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
}

public void Stop()
{
listener.Stop();
listenerThread.Abort();
}

private void Listen()
{
while (true)
{
try
{
//Waits for a connection.
Socket request = listener.AcceptSocket();
//Trace.TraceInformation("Connection accepted from {0}", request.RemoteEndPoint);
new Thread(new ThreadStart(() => HandleRequest(request))).Start();
}
catch (Exception ex)
{
//Trace.TraceInformation(ex.Message);
}
}
}

private void HandleRequest(Socket client)
{
DateTime fecha = DateTime.Now;
byte[] response = new byte[1]{0x00};
byte[] data = new byte[7];
byte crc;
double temperatura;

client.Receive(data);

crc = (byte)(data[1] + data[2] + data[3] + data[4]);
if (data[5] == crc)
{
temperatura = data[3];
temperatura += data[4] / 100.00;
//Trace.TraceInformation("Temperatura actual: {0}ºC", temperatura);
if (RealDevice(data[1]))
{
if (InsertData(data[1], data[2], temperatura))
{
response[0] = 0xFF;
}
}
}
client.Send(response);
client.Close();
}

/// <summary>
/// Checks whether the device exists or not.
/// </summary>
/// <param name="deviceId">The device's ID.</param>
/// <returns>True if exists, false if not.</returns>
private bool RealDevice(byte deviceId)
{
MySqlCommand command;
MySqlDataReader reader;
bool successful = true;
string query = "SELECT id FROM dispositivos WHERE id = @device";
//Trace.TraceInformation("Initializing connection to database...");
databaseConnection = new MySqlConnection(connectionString);
//Trace.TraceInformation("Connection to database successful!");
try
{
using (databaseConnection)
{
command = new MySqlCommand(query, databaseConnection);
command.Parameters.AddWithValue("@device", deviceId);
databaseConnection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
if (!reader.HasRows)
{
successful = false;
}
}
databaseConnection.Close();
}
}
catch (Exception ex)
{
//Trace.TraceInformation(ex.Message);
}
return successful;
}

/// <summary>
/// Inserts the data from the device.
/// </summary>
/// <param name="deviceId">Device's ID.</param>
/// <param name="sensorId">Sensor that sends the data.</param>
/// <param name="value">Data value.</param>
/// <returns>True if successful, false if not.</returns>
private bool InsertData(byte deviceId, byte sensorId, double value)
{
bool successful = true;
MySqlCommand command;
DateTime date = DateTime.Now.ToUniversalTime();
TimeZoneInfo localTime = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time (Mexico)");
date = TimeZoneInfo.ConvertTimeFromUtc(date, localTime);
string query = "INSERT INTO datos (valor, fecha, hora, id_dispositivo, id_sensor) "+
"VALUES (@valor, @fecha, @hora, @id_dispositivo, @id_sensor)";
databaseConnection = new MySqlConnection(connectionString);
try
{
using (databaseConnection)
{
command = new MySqlCommand(query, databaseConnection);
command.Parameters.AddWithValue("@valor", value);
command.Parameters.AddWithValue("@fecha", date.ToString("yyyy-MM-dd"));
command.Parameters.AddWithValue("@hora", date.ToString("HH:mm:ss"));
command.Parameters.AddWithValue("@id_dispositivo", deviceId);
command.Parameters.AddWithValue("@id_sensor", sensorId);
databaseConnection.Open();
command.ExecuteNonQuery();
databaseConnection.Close();
}
}
catch (Exception ex)
{
//Trace.TraceInformation(ex.Message);
successful = false;
}
return successful;
}
}
}

最佳答案

您可能应该将监听工作移至主线程。这解决了阻塞问题(因为你想要阻塞)。没有必要有一个专门用于监听的线程。

如果你不想要这样:

Thread.Sleep(Timeout.Infinite);

关于mysql - 为什么我的辅助角色在 Azure 上使用了高达 99% 的 CPU?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25088997/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com