【发布时间】:2020-06-25 01:31:32
【问题描述】:
我有一个用 C# 编写的程序,用于分析来自外部 API 的文本数据。 主要部分看起来像
Main.cs
void main {
var data = new HttpRequest();
while (true) {
string response = data.Get("https://api.com/method/").ToString();
JObject json = JObject.Parse(response);
if (Convert.ToString(json["updates"][i]["type"]) == "message_new") {
Data new_data = new Data();
new_data.Text = json["updates"][i]["text"].ToString();
.... //filling class new_data//....
Thread thread = new Thread(() => ProcessMsg(new_data));
thread.Start();
} else { //nothing}
}
}
数据类
public class Data
{
public string Token = "alof23321cdfds34rf32rty5";
public string Token_Usr = "fsdfdsf3432";
public static string GroupId = "3331122";
public int Time { get; set; }
public int IdUser { get; set; }
public int IdConf { get; set; }
public int IdMessage { get; set; }
public string Text { get; set; }
}
但很多时候(当 2 条消息同时到达时)信息在这些线程中混合(竞争条件?) 如何使线程中传递的类只能从此线程访问?也许我应该为此使用其他东西?
p.s不关注代码,我只是尝试重现逻辑。
【问题讨论】:
标签: c# multithreading thread-safety