In my Asp.Net web service i use below 2 method to change an existing client's status form a global list oblject named ClientStatus here. This global list is modified from several client side but in a safe way (lock).
private static List<ActiveClient> ClientStatus = new List<ActiveClient>();
public static void SetClinetStatus(string ClientID, int clinetstatus)
{
ActiveClient activeClient=null;
try
{
activeClient = GetClient(ClientID);
if (activeClient != null)
{
activeClient.statuschanged = true;
activeClient.status = clinetstatus;
}
}
catch (Exception ex)
{
WebserviceLog.Debug(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + "::" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + ":" + ex.Message);
}
}
public static ActiveClient GetClient(string clientID)
{
ActiveClient activeClient = null;
try
{
lock (ClientStatus)
{
activeClient = ClientStatus.Find(c => c.clinetID == clientID);
}
}
catch (Exception ex)
{
throw ex;
}
return activeClient;
}
I used below code to pass the value to SetClinetStatus(string ClientID, int clinetstatus) method
string errorData = Encoding.Default.GetString(data);
string[] tokens = errorData.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length == 2)
{
SessionVariables.SetClinetStatus(tokens[0],Convert.ToInt32(tokens[1]));
}
But sometimes (not every times) i get
Object reference not set to an instance of an object
form
activeClient = GetClient(ClientID);
i don't understand why it is happening and don't see any problem there.
does anyone see any problem there that is responsible for such kind of exception.
EDIT
In the global list i only add client through below method and here clientID will come from direct webservice method. and in another end (from where the client ID comes) i added a check for not to null or empty the clientID.
public static void AddClient(string clientID)
{
try
{
lock (ClientStatus)
{
ClientStatus.Add(new ActiveClient { clinetID = clientID });
}
}
catch (Exception ex)
{
WebserviceLog.Debug(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType + "::" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + ":" + ex.Message);
}
}
and the ActiveClient
class structure is
public class ActiveClient
{
public ActiveClient()
{
clinetID = string.Empty;
status = 0;
statuschanged = false;
}
public string clinetID { get; set; }
public int status { get; set; }
public bool statuschanged { get; set; }
}