关于线程的一点困惑,我写了个脚本批量往数据库里填数据。直接一股脑填卡电脑,所以开了个线程让它一点点往里填,但是我发现我unity停止线程仍在执行(debug一直在输出且数据库不断有数据加入)。我没有写线程关闭的逻辑,因为我理解的unity里面的线程都属于子线程,会随着unity主线程的关闭而关闭,所以出现这一幕挺困惑的,也找不到太好的说明,希望大家帮忙解惑。
using System.Collections;
using System.Collections.Generic;
using MySql.Data.MySqlClient;
using UnityEngine;
using System.IO;
using System.Threading;
public class MysqlOp : MonoBehaviour
{
const string firt = "-";
const string second = "--";
const string third = "---";
int id = 0;
int parentID = -1;
int parentID2=-1;
MySqlConnection conn;
// Start is called before the first frame update
void Start()
{
ConnectMysql();
Thread t=new Thread(ReadFile);
t.Start();
}
// Update is called once per frame
void Update()
{
}
void ReadFile()
{
string path = Application.streamingAssetsPath + "/1.txt";
string[] arr = File.ReadAllLines(path);
for (int i = 0; i < arr.Length; i++)
{
id++;
string[] temp = arr[i].Split('>');
if (temp[1].StartsWith(firt) && !temp[1].StartsWith(second) && !temp[1].StartsWith(third))
{
parentID=id;
parentID2=0;
Debug.Log(temp[1]);
Insert(id,"0",temp[1].Replace(firt,""),"1");
}
if (temp[1].StartsWith(second) && !temp[1].StartsWith(third))
{
parentID2=id;
Debug.Log("二级结构:"+temp[1]);
Insert(id,parentID.ToString(),temp[1].Replace(second,""),"2");
}
if (temp[1].StartsWith(third))
{
Insert(id,parentID2.ToString(),temp[1].Replace(third,""),"3");
}
Thread.Sleep(500);
}
}
void ConnectMysql()
{
string sqlSer = "server = localhost;port = 3306;database = db_whlearn;user = root;password = root";
//建立连接
conn = new MySqlConnection(sqlSer);
try
{
conn.Open();
Debug.Log("------链接成功------");
//sql语句
}
catch (System.Exception e)
{
Debug.Log(e.Message);
}
}
void Insert(int id, string pid, string name,string leader)
{
string sqlQuary = "insert into ums_dept(id,parent_id,dept_name,leader) values (@id, @parent_id,@dept_name,@leader)";
MySqlCommand comd = new MySqlCommand(sqlQuary, conn);
comd.Parameters.AddWithValue("@id", id);
comd.Parameters.AddWithValue("@parent_id", pid);
comd.Parameters.AddWithValue("@dept_name", name);
comd.Parameters.AddWithValue("@leader", leader);
comd.ExecuteNonQuery();
}
}