ArtemiZ Studio
ArtemiZ Studio

Reputation: 177

How to create new class object for every new thread?

I have a programm written in C# which use for analysis text data from external API. The main section looks like

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}
  }

 }

Data Class

 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; }
    }

But very often (when 2 messages arrive at the same time) information is mixed in these threads (race condition?) How to make the passed class in thread accessible only from this thread? Maybe I should use something else for this?

p.s do not pay attention to the code, I just tried to reproduce the logic.

Upvotes: 1

Views: 549

Answers (1)

Gusman
Gusman

Reputation: 15151

You are creating a closure when you do Thread thread = new Thread(() => ProcessMsg(new_data));. If something changes new_data before the delegate is executed it will "see" the new version when run, what you are experiencing.

Thread has two constructors, one accepting a ThreadStart delegate and other accepting a ParameterizedThreadStart delegate and an object, in this case you want to use the later to pass the patameter to your thread function, something like this:

//...
Thread thread = new Thread(ProcessMsg, new_data);


//..
public void ProcessMsg(object State)
{
    var data = (Data)State;
    //Process the data
}

Upvotes: 1

Related Questions