user222427
user222427

Reputation:

Thread safe public string

I have a public string that is set from data inside of a DataTable, i'm looking for an example on how to make it multithreading safe

public string Server { get; set; }

string Server = DT.Rows[0].ItemArray[0].ToString();

This is what I have however, i don't think this is safe when all other threads set their string Server based on data inside of the datatable.

Upvotes: 4

Views: 1033

Answers (1)

payo
payo

Reputation: 4561

From your comments to your original post, I think what you want is ThreadLocal

You'd get:

// declared as:
ThreadLocal<string> Server;

// ... initialized by:
Server = new ThreadLocal(() => DT.Rows[0].ItemArray[0].ToString());

In each thread the string here would be unique to that thread.

If you want the first thread to win (lazy load model) then use the following Lazy

// declared as:
Lazy<string> Server;

// ... initialized by:
Server = new Lazy(() => DT.Rows[0].ItemArray[0].ToString());

In each thread the string here would be shared, and only the first thread would load it.

Upvotes: 5

Related Questions