2 different implementations of buffer
Hello,
I have a class containing network incoming buffer and multiple threads trying to access it. I had to add a ManualResetEvent to act as a token preventing simultaneous access.
I have an idea of a new implementation but I may be wrong, could you give me your ideas ?
1st and current implementation
Code:
static public class IncomingBuffer
{
private static StringBuilder mySb = new StringBuilder();
public static int numberOfSentence=0;
private static ManualResetEvent locksb = new ManualResetEvent(true);
public static string GetFirstSentenceAndRemove()
{
locksb.WaitOne();
locksb.Reset();
string s = mySb.ToString();
int i = s.IndexOf("#END#");
if (i > -1)
{
string[] ss = Regex.Split(s, "#END#");
mySb.Clear();
mySb.Append(s.Remove(0, i + 5));
numberOfSentence--;
locksb.Set();
return ss[0];
}
else
{
numberOfSentence = 0;
locksb.Set();
return string.Empty;
}
}
public static void Clear()
{
mySb.Clear();
}
public static bool CheckIfContainAnySentence()
{
locksb.WaitOne();
locksb.Reset();
string s;
try
{
s = mySb.ToString();
}
catch (Exception)
{
locksb.Set();
return false;
}
locksb.Set();
int i = s.IndexOf("#END#");
if (i > -1)
return true;
else
return false;
}
public static void AppendData(string s)
{
mySb.Append(s);
}
}
2nd and maybe new implementation
Code:
static public class IncomingBuffer
{
private static string data;
public static int numberOfSentence=0;
private static ManualResetEvent locksb = new ManualResetEvent(true);
public static string GetFirstSentenceAndRemove()
{
locksb.WaitOne();
locksb.Reset();
int i = data.IndexOf("#END#");
if (i > -1)
{
string[] ss = Regex.Split(data, "#END#");
data = data.Remove(0, i + 5);
numberOfSentence--;
locksb.Set();
return ss[0];
}
else
{
numberOfSentence = 0;
locksb.Set();
return string.Empty;
}
}
public static void Clear()
{
data = string.Empty;
}
public static bool CheckIfContainAnySentence()
{
locksb.WaitOne();
locksb.Reset();
int i = data.IndexOf("#END#");
locksb.Set();
if (i > -1)
return true;
else
return false;
}
public static void AppendData(string s)
{
locksb.WaitOne();
locksb.Reset();
StringBuilder sb = new StringBuilder();
sb.Append(data);
s = sb.Append(s).ToString();
locksb.Set();
}
}
Which one of them looks bettter ?
EDIT : numberofsentences is incremented by the stream itself. my stream looks like this
Code:
data#data#data##END#data#data#data#data##END#....
thread only process from #END# to #END#
Re: 2 different implementations of buffer
Did you try any of .NET thread-safe collection classes before implementing your own?
http://msdn.microsoft.com/en-us/libr...oncurrent.aspx