Hi guys,
please check my code,
private void ButtonStartUp_Click(object sender, EventArgs e)
{
for (int i = 0; i < maxthread; i++)
{
QHThreadArray[i] = new TQHThread();
QHThreadArray[i].ThreadNo = i;
QHThreadArray[i].QH_id = QH_id;
QHThreadArray[i].Start();
}
}
private void Button_UpdateOS_Click(object sender, EventArgs e)
{
fileName = "osdays.csv";
if (!File.Exists(fileName))
{
MessageBox.Show(fileName + "File Does Not Exist!");
}
else if (File.Exists(fileName))
{
sendNextRequestFromList();
}
}
public static void sendNextRequestFromList()
{
while (DBPendingList.Count > 0)
{
int ThNum = -1;
QH = null;
for (int i = 0; i < maxthread; i++)
{
if (QHThreadArray[i].Status == "Running")
{
continue;
}
if (QHThreadArray[i].Status == "Suspended")
{
QH = QHThreadArray[i];
ThNum = i;
break;
}
}
if (ThNum == -1)
break;
if (QH != null)
{
QH.RequestStr = DBPendingList[0];
DBPendingList.RemoveAt(0);
QH.Resume();
}
}
if (DBPendingList.Count != 0)
{
ret = new retFreeThreadDelegate(sendNextRequestFromList);
ret.BeginInvoke(null, null);
}
}
public class TQHThread
{
public int ThreadNo;
public string QH_id;
public string RequestStr=null;
public SqlCommand cmd;
public SqlConnection con;
public Thread t;
public readonly object locker = new object();
public int result = -1;
public void Start()
{
t = new Thread(new ThreadStart(this.Execute));
t.Start();
}
public void Resume()
{
if (Status == "Suspended")
t.Resume();
}
public void Suspend()
{
if (Status == "Running")
{
t.Suspend();
}
}
public string Status
{
get
{
return t.ThreadState.ToString();
}
}
public void Execute()
{
con = new SqlConnection(File.ReadAllText("Connection" + QH_id + ".udl"));
cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
if (RequestStr == null)
{
Suspend();
}
while (this.Status != "Suspended")
{
try
{
cmd.CommandText = RequestStr;
result=cmd.ExecuteNonQuery();
}
catch (SqlException)
{
}
catch (InvalidOperationException)
{
}
frmQuoteHandler.UpdateDBComplete(this);
}
}
}
we want to return result to the main thread in UpdateDBComplete().
public static void UpdateDBComplete(TQHThread QH)
{
lock (locker)
{
if (QH != null)
{
int x = QH.result;
QH.Suspend();
}
}
}</string>
in case code is working bit properly BUT AFTER GETTING RESULT OUT OF THREAD OR WHENEVER A THREAD IS FREE TO WORK, I want to call
"sendNextRequestFromList()"
again in the MAIN thread, i.e. I am unable to perform so need your suggestion.
For time being its working because of the BeginInvoke is used but its not the logically correct and the way I want.
and just tell me the possible ways that i can call
"sendNextRequestFromList()"
in the MAIN thread whenever result obtained or whenever a particular thread is free.
waiting for soon reply, and Thanks in advance.
[Edited]Code is wrapped in "pre" tag[/Edited]