I have an online chat code, there is a list of logged in users on the system. There is a problem adding the users name in the listBox; The error is as follows: Invalid thread operation: control 'lbClients' accessed from a thread that is not the one in which it was created.
I tried the Invoke method, but it also did not work. With the Invoke method, the server adds the user to the list, but when the user disconnects, the list of users logged on to the server does not refresh. What can be done?
public void ServiceClient()
{
Socket client = clientsocket;
bool keepalive = true;
while (keepalive)
{
Byte[] buffer = new Byte[1024];
client.Receive(buffer);
string clientcommand = System.Text.Encoding.ASCII.GetString(buffer);
string[] tokens = clientcommand.Split(new Char[]{'|'});
Console.WriteLine(clientcommand);
if (tokens[0] == "CONN")
{
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
SendToClient(cl, "JOIN|" + tokens[1]);
}
EndPoint ep = client.RemoteEndPoint;
//string add = ep.ToString();
Client c = new Client(tokens[1], ep, clientservice, client);
this.Invoke(new Action(() => clients.Add(c)));
string message = "LIST|" + GetChatterList() +"\r\n";
SendToClient(c, message);
try
{
lbClients.Items.Add(c);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
else if (tokens[0] == "CHAT")
{
for(int n=0; n<clients.Count; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
}
}
else if (tokens[0] == "PRIV")
{
string destclient = tokens[3];
for(int n=0; n<clients.Count; n++) {
Client cl = (Client)clients[n];
if(cl.Name.CompareTo(tokens[3]) == 0)
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
SendToClient(cl, clientcommand);
}
}
else if (tokens[0] == "GONE")
{
int remove = 0;
bool found = false;
int c = clients.Count;
for(int n=0; n<c; n++)
{
Client cl = (Client)clients[n];
SendToClient(cl, clientcommand);
if(cl.Name.CompareTo(tokens[1]) == 0)
{
remove = n;
found = true;
lbClients.Items.Remove(cl);
//lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
}
}
if(found)
this.Invoke(new Action(() => clients.RemoveAt(remove)));
client.Close();
keepalive = false;
}
else
{
int remove = 0;
bool found = false;
int c = clients.Count;
for (int n = 0; n < c; n++)
{
Client cl = (Client)clients[n];
//SendToClient(cl, clientcommand);
if (cl.Name.CompareTo(tokens[1]) == 0)
{
remove = n;
found = true;
lbClients.Items.Remove(cl);
//lbClients.Items.Remove(cl.Name + " : " + cl.Host.ToString());
}
}
if (found)
clients.RemoveAt(remove);
client.Close();
keepalive = false;
}
}
}
i use the Asynchronous socket Client event to receive message from server.
i receive message from client DataIn(my Event Name) and add to list box ,but not happen to show on UI!
protected void WebSocketClientControl1_OnChatNotification(List < SocketUi > sender) {
ClientScript.RegisterStartupScript(GetType(), "hwa", "javascript:__doPostBack('WebSocketClientControl1','')", true);
}
i cant use the (Response.Redirect & Server.Transfer).
this 2 function have error run time.
i call the javaScript function to show message , not happen on screen.
its my Socket code
public delegate void OnChatNotification(List<SocketUi> sender);
public class WebSocketClientControl : System.Web.UI.Control, IPostBackDataHandler
{
public static ClientService _internalClientService = new ClientService(DServerConfig.ServerAddress.ToString(),
DServerConfig.ServerSoketPort);
public event OnChatNotification OnChatNotification = delegate { };
public WebSocketClientControl()
{
_internalClientService.OnChat += _internalClientService_OnChat;
}
public void Connect(long userID, SocketEnums.EntityType usertype, string username, string key)
{
_internalClientService.Connect(userID, usertype, username, key);
}
private void _internalClientService_OnChat(List<SocketUI.SocketUi> sender)
{
if (OnChatNotification != null)
OnChatNotification(sender);
}
public bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
String presentValue = postDataKey;
String postedValue = postCollection[postDataKey];
if (presentValue == null || !presentValue.Equals(postedValue))
{
return true;
}
return false;
}
public void RaisePostDataChangedEvent()
{
}
}
its my ui Code
private void WebSocketClientControl1_OnChatNotification(List<SocketUI.SocketUi> sender)
{
foreach (SocketUi socketUi in sender)
{
switch (socketUi.DSocketType)
{
case SocketEnums.DSocketType.Chat:
foreach (SocketUI.tb_Chat chatUi in socketUi.Chats)
{
for (int i = 0; i < ASPxPageControl1.TabPages.Count; i++)
{
if (ASPxPageControl1.TabPages[i].Name == "uxTabPage_" + _channels[i].ID.ToString())
{
switch (chatUi.ChatMessegeType)
{
case (int)Enums.ChatMessegeType.Message:
SetNewMessageOnUi(HelperD.UiChat_To_Tb_Chat(chatUi));
break;
case (int)Enums.ChatMessegeType.Readed:
break;
case (int)Enums.ChatMessegeType.OnLinedUser:
break;
case (int)Enums.ChatMessegeType.OffLinedUser:
break;
case (int)Enums.ChatMessegeType.JoinChannle:
case (int)Enums.ChatMessegeType.LeftChannle:
GetUserChannel(chatUi.ChannelID.ID);
break;
case (int)Enums.ChatMessegeType.TypingUser:
for (int j = 0; j < ASPxPageControl1.TabPages[i].Controls.Count; j++)
{
if (ASPxPageControl1.TabPages[i].Controls[j] is System.Web.UI.WebControls.Label &&
ASPxPageControl1.TabPages[i].Controls[j].ID ==
"uxLabel_Status" + ASPxPageControl1.TabPages[i].DataItem.ToString())
{
System.Web.UI.WebControls.Label uxLabel_StatusTemp = new System.Web.UI.WebControls.Label();
uxLabel_StatusTemp = (System.Web.UI.WebControls.Label)ASPxPageControl1.TabPages[i].Controls[j];
uxLabel_StatusTemp.Text = " درحال تایپ " + socketUi.UserName + "...";
// timer1.Start();
}
}
break;
}//End For
// listBox_Message.Items.Add("Me:=>" + chatUi.Message + "\n\r");
}
}
}//End For
break;
}
}
}
private void SetNewMessageOnUi(UiSideLanguage.Database.Chat.tb_Chat item)
{
ASPxTextBox_Message.Text = "";
for (int i = 0; i < ASPxPageControl1.TabPages.Count; i++)
{
for (int j = 0; j < ASPxPageControl1.TabPages[i].Controls.Count; j++)
{
if (ASPxPageControl1.TabPages[i].Controls[j] is System.Web.UI.WebControls.ListBox && ASPxPageControl1.TabPages[i].Controls[j].ID == "uxListView_Chat" + ASPxPageControl1.TabPages[i].DataItem.ToString())
{
System.Web.UI.WebControls.ListBox userListView = (System.Web.UI.WebControls.ListBox)ASPxPageControl1.TabPages[i].Controls[j];
System.Web.UI.WebControls.ListItem listViewItemTemp = new System.Web.UI.WebControls.ListItem();
if (item.AddUser.ID == Language.CacheEntity.CurrentUser.ID)
{
listViewItemTemp.Text = " :من " + item.Message;
// listViewItemTemp.ForeColor = Color.DarkCyan;
}
else
{
listViewItemTemp.Text = item.AddUser.UserName + " : " + item.Message;
// listViewItemTemp.ForeColor = Color.DarkRed;
}
listViewItemTemp.Value = item.MessageFlagID.ToString();
System.Web.UI.WebControls.ListItem isHaveChatItem = null;
foreach (System.Web.UI.WebControls.ListItem chatitemListView in userListView.Items)
{
if (Language.HelperD.GetLong(chatitemListView.Value) == item.MessageFlagID)
{
isHaveChatItem = chatitemListView;
break;
}
}
if (isHaveChatItem != null)
{
if (item.AddUser.ID == Language.CacheEntity.CurrentUser.ID)
{
isHaveChatItem.Text = " :من " + item.Message;
// isHaveChatItem.ForeColor = Color.DarkCyan;
}
else
{
isHaveChatItem.Text = item.ToUser.UserName + " : " + item.Message;
// isHaveChatItem.ForeColor = Color.DarkRed;
}
isHaveChatItem.Value = item.MessageFlagID.ToString();
}
else
{
userListView.Items.Add(listViewItemTemp);
}
}
}
}
}
This function for Update UI >>> SetNewMessageOnUi
I Create Objects on Runtime.
this code is worked
userListView.Items.Add(listViewItemTemp);
and ListView Have Item But On UI Not set.
all objects in the UpdatePanle
I am having some trouble with the verse button. i am not sure what I am doing wrong but I need to make it where the user presses the verse button and it adds the textview of the word "Verse" to the list that was created. Please help. What am I doing wrong. This was written for Android using C# in Xamarin by the way.
namespace Songression
{
public class CheckRect{
public int top{ get; set; }
public int height{ get; set; }
}
[Activity (Label = "Songression")]
public class results : Activity, View.IOnTouchListener
{
//CheckBox[] check;
List<LinearLayout> linearSet;
//List<CheckRect> rectList;
ScrollView scrollView;
EditText editText = null;
LinearLayout view;
bool moveOrEdit = false;
int screenWidth;
List<String> checkTextList;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.results);
var metrics = Resources.DisplayMetrics;
screenWidth = metrics.WidthPixels;
//var widthInDp = ConvertPixelsToDp(metrics.WidthPixels);
view = FindViewById<LinearLayout> (Resource.Id.linearlayout0);
checkTextList = new List<String>();
checkTextList.Add ("10 bucks in your pocket and barely making it.");
checkTextList.Add ("100 steps to the water");
checkTextList.Add ("18 and going to Hollywood");
checkTextList.Add ("3 years to propose");
String checkTextSet = Intent.GetStringExtra ("MyData") ?? "";
if (checkTextSet == null || checkTextSet == "") {
} else {
String[] textSet = checkTextSet.Split (',');
checkTextList.AddRange (textSet);
}
//Back Button
Button buttonBack = FindViewById<Button> (Resource.Id.buttonBack);
buttonBack.Click += delegate {
Finish();
};
///
//AddLine Button
Button buttonAdd = FindViewById<Button> (Resource.Id.buttonAdd);
buttonAdd.Click += delegate {
addTextPro(false,"");
};
///
//Add Verse
//Button buttonVerse = FindViewById <Button> (Resource.Id.buttonVerse);
//buttonVerse.Click += delegate {
// checkTextList.Add("Verse"));
//};
{
///
//Email Button
Button buttonEmail = FindViewById<Button> (Resource.Id.buttonEmail);
buttonEmail.Click += delegate {
runEmailPro ();
};
scrollView = FindViewById<ScrollView> (Resource.Id.scrollview0);
List<String> resultList = new List<String> ();
int count = checkTextList.Count;//myResources.check_indexSet.Count;
linearSet = new List<LinearLayout> ();
for (int index = 0; index < view.ChildCount; index++) {
view.RemoveViewAt (index);
}
///
//Initiate Rect and Check
if (myResources.isLast == false) {
for (int index = 0; index < count; index++) {
InitiateWidgets (index, false);
}
} else {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
var lastPath = Path.Combine (sdCardPath, "lastlasttxt.txt");
String fileNamePath = Path.Combine (sdCardPath, readFileSdcardFile (lastPath));
String loadData;
if (File.Exists (fileNamePath))
loadData = File.ReadAllText (fileNamePath);
else
return;
String[] splitData = loadData.Split ('\n');
foreach (String item in splitData) {
if (item.CompareTo ("") == 0)
continue;
if (item [0] == 't') {
addTextPro (true, item.Substring (1));
}
if (item [0] == 'c') {
bool bChecked = false;
if (item [1] != '0') {
bChecked = true;
} else {
bChecked = false;
}
InitiateWidgets (0, true, item.Substring (2), bChecked);
}
}
}
///
//save function
Button buttonSave = FindViewById<Button> (Resource.Id.buttonSave);
buttonSave.Click += delegate {
saveResultPro ();
};
///
//move function
Button buttonMove = FindViewById<Button> (Resource.Id.buttonMove);
buttonMove.Text = "Move";
buttonMove.Click += delegate {
removeAllFocus (moveOrEdit);
if (moveOrEdit == false) {
buttonMove.Text = "Edit";
moveOrEdit = true;
} else {
buttonMove.Text = "Move";
moveOrEdit = false;
}
};
//final function
Button buttonFinal = FindViewById<Button> (Resource.Id.buttonFinal);
buttonFinal.Click += delegate {
var fResults = new Intent (this, typeof(finalResults));
fResults.PutExtra ("MyData", getAllInfo ());
StartActivity (fResults);
};
}
}
//wirte the file on the sdcard.
public void writeFileSdcardFile(String path,String write_str,bool bTitle){
if (bTitle == true) {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
var lastPath = Path.Combine(sdCardPath,"lastlasttxt.txt");
if (File.Exists (path) == false) {
File.WriteAllText (path, write_str);
}
else {
String[] existFile = readFileSdcardFile (path).Split('\n');
foreach (String item in existFile) {
if (write_str.Substring (0, write_str.Length - 1).CompareTo (item) == 0) {
File.WriteAllText (lastPath, write_str.Substring (0, write_str.Length - 1));
return;
}
}
File.AppendAllText (path, write_str);
}
File.WriteAllText (lastPath, write_str.Substring(0, write_str.Length - 1));
} else {
File.WriteAllText (path, write_str);
}
}
public String readFileSdcardFile(String path) {
if (File.Exists (path))
return File.ReadAllText (path);
else
return "";
}
public String getAllInfo()
{
String extra = "";
foreach(LinearLayout linear in linearSet)
{
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
extra += editText.Text + "\n";
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
if (checBox.Checked == true)
extra +="1" + checBox.Text + "\n";
else
extra +="0" + checBox.Text + "\n";
}
}
return extra;
}
//
//run email pro
public void runEmailPro(){
var email = new Intent (Android.Content.Intent.ActionSend);
email.PutExtra (Android.Content.Intent.ExtraEmail,
new string[]{"person1#xamarin.com", "person2#xamrin.com"} );
email.PutExtra (Android.Content.Intent.ExtraCc,
new string[]{"person3#xamarin.com"} );
email.PutExtra (Android.Content.Intent.ExtraSubject, "Hello Email");
email.PutExtra (Android.Content.Intent.ExtraText,
getAllInfo());
email.SetType ("message/rfc822");
StartActivity (email);
}
//
// add Text code
public void addTextPro(bool bLast,String textWidget)
{
LinearLayout linear = new LinearLayout (this);
ImageView imgView = new ImageView (this);
imgView.SetImageResource (Resource.Drawable.delete123);
editText = new EditText (this);
editText.SetSingleLine ();
editText.SetWidth(screenWidth - 50);
if (bLast)
editText.Text = textWidget;
if (moveOrEdit == true)
editText.SetOnTouchListener (this);
else
editText.SetOnTouchListener (null);
linear.AddView(editText);
linear.AddView(imgView);
//delete function.
imgView.Click += delegate {
deleteMessage(imgView);
};
linearSet.Add(linear);
view.AddView(linear);
}
//
//delete message
public void deleteMessage(ImageView imgView)
{
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Delete Phrase!");
builder.SetMessage ("Are you sure you would like to delete this phrase?");
builder.SetPositiveButton("Yes", (sender, args) => {
// Yes button
LinearLayout parent = (LinearLayout)imgView.Parent;
parent.Visibility = ViewStates.Invisible;
int childIndex = view.IndexOfChild(parent);
view.RemoveView(parent);
linearSet.Remove(parent);});
builder.SetNegativeButton("No", (sender, args) => {});
builder.SetCancelable(false);
builder.Show ();
}
//
//save Result
public void saveResultPro()
{
var factory = LayoutInflater.From(this);
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Song Name");
EditText songText = new EditText (this);
builder.SetView (songText);
//builder.SetView(factory.Inflate(Resource.Layout.saveDialog,
// FindViewById<ViewGroup>(Resource.Id.saveDialog)));
builder.SetPositiveButton("OK", (sender, args) => {
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.Path;
//EditText songText = FindViewById<EditText> (Resource.Id.projectName);
var textPath = Path.Combine(sdCardPath,songText.Text);
var textTitlePath = Path.Combine(sdCardPath,"Titles.txt");
String saveData = "";
foreach(LinearLayout linear in linearSet)
{
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
saveData += "t" + editText.Text + "\n";
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
if (checBox.Checked == true)
saveData += "c1" + checBox.Text + "\n";
else
saveData += "c0" + checBox.Text + "\n";
}
}
writeFileSdcardFile(textTitlePath,songText.Text + "\n",true);
writeFileSdcardFile(textPath,saveData,false);
});
builder.SetNegativeButton("Cancel", (sender, args) => {});
builder.SetCancelable(false);
builder.Show ();
}
//remove All focus
public void removeAllFocus(bool flag){
View.IOnTouchListener context = null;
if (flag == false){
context = this;
}
else{
context = null;
}
foreach (LinearLayout linear in linearSet) {
var widgetType = linear.GetChildAt (0).GetType ().ToString ();
if (widgetType.CompareTo ("Android.Widget.EditText") == 0) {
EditText editText = (EditText)linear.GetChildAt (0);
editText.SetOnTouchListener (context);
} else if (widgetType.CompareTo ("Android.Widget.CheckBox") == 0) {
CheckBox checBox = (CheckBox)linear.GetChildAt (0);
checBox.SetOnTouchListener (context);
}
}
scrollView.SetOnTouchListener (context);
}
//
//initiate widgets
public void InitiateWidgets(int index,bool bLast,String widgetText = "", bool bSel = false){
LinearLayout linear = new LinearLayout (this);
CheckBox check = new CheckBox(this);
ImageView imgView = new ImageView (this);
//delete function.
imgView.Click += delegate {
deleteMessage(imgView);
};
if (bLast == false) {
//int stringIndex = Resource.String.checkname0 + myResources.check_indexSet [index];
check.Text = checkTextList[index];
if (index < 4) {
if (myResources.check_index [index] == 1)
check.Checked = true;
else {
check.Checked = false;
}
} else {
check.Checked = true;
}
} else {
check.Text = widgetText;
check.Checked = bSel;
}
check.SetWidth (screenWidth - 55);
check.SetOnTouchListener (null);
imgView.SetImageResource (Resource.Drawable.delete123);
linear.AddView (check);
linear.AddView (imgView);
linearSet.Add(linear);
view.AddView (linear);
scrollView.SetOnTouchListener (null);
}
//
//Touch Event
float _viewY = 0;
//bool flag = false;
bool check_flag = false;
LinearLayout parentLayout;
int selTop;
int selBottom;
bool downFlag = false;
public bool OnTouch(View v, MotionEvent e)
{
switch (e.Action)
{
case MotionEventActions.Down:
if (v != scrollView) {
_viewY = e.GetY ();
parentLayout = (LinearLayout)v.Parent;
selTop = parentLayout.Top;
selBottom = parentLayout.Bottom;
check_flag = true;
downFlag = true;
}
break;
case MotionEventActions.Move:
if (v == scrollView && downFlag == true) {
var top = (int)(e.GetY () - _viewY);
var bottom = (int)(top + 55);
parentLayout.Layout (parentLayout.Left, top, parentLayout.Right, bottom);
check_flag = false;
}
break;
case MotionEventActions.Up:
if (downFlag == false)
return true;
if (parentLayout == null)
return true;
int originalPos = 0;
int placePos = -1;
downFlag = false;
if (parentLayout.GetChildAt(0).GetType ().ToString ().CompareTo ("Android.Widget.CheckBox") == 0) {
if (check_flag == true) {
CheckBox selCheck = (CheckBox)parentLayout.GetChildAt (0);
if (selCheck.Checked == false) {
selCheck.Checked = true;
} else {
selCheck.Checked = false;
}
check_flag = false;
return true;
}
}
if (parentLayout.GetChildAt(0).GetType ().ToString ().CompareTo ("Android.Widget.EditText") == 0) {
if (check_flag == true) {
EditText selText = (EditText)parentLayout.GetChildAt (0);
check_flag = false;
return true;
}
}
if (v == scrollView) {
int linearCount = linearSet.Count;
int index;
for (index = 0; index < linearCount; index++) {
if (parentLayout == linearSet [index]) {
originalPos = index;
break;
}
}
//Laying position.
for (index = 0; index < linearCount; index++) {
if (originalPos == index)
continue;
if (linearSet[originalPos].Top < linearSet [index].Top) {
if (originalPos == index - 1) {
linearSet[originalPos].Layout (linearSet[originalPos].Left,
selTop, linearSet[originalPos].Right,
selBottom);
return true;
} else {
if (index > originalPos) {
placePos = index - 1;
break;
} else {
placePos = index;
break;
}
}
}
/*if (linearSet [originalPos].Top == linearSet [index].Top) {
linearSet[originalPos].Layout (linearSet[originalPos].Left,
selTop, linearSet[originalPos].Right,
selBottom);
return true;
}*/
}
//Is original pos?
if ((originalPos == linearCount - 1) && (placePos == -1)) {
linearSet[originalPos].Layout (linearSet[originalPos].Left, selTop,
linearSet[originalPos].Right, selBottom);
return true;
}
if (placePos == -1)
placePos = linearCount - 1;
//Change the position on the result page.
int orgTop;
int orgBottom;
orgTop = linearSet [originalPos].Top;
orgBottom = linearSet [originalPos].Bottom;
linearSet [originalPos].Layout (linearSet[originalPos].Left, linearSet [placePos].Top,
linearSet[originalPos].Right, linearSet [placePos].Bottom);
LinearLayout tempLinear = linearSet [originalPos];
if (originalPos >= placePos) {
for (index = originalPos - 1; index >= placePos; index--) {
linearSet [index].Layout (linearSet[originalPos].Left, linearSet [index + 1].Top,
linearSet[originalPos].Right, linearSet [index + 1].Bottom);
linearSet [index + 1] = linearSet [index];
}
} else {
for (index = originalPos + 1; index <= placePos; index++){
linearSet [index].Layout (linearSet[originalPos].Left, linearSet [index - 1].Top,
linearSet[originalPos].Right, linearSet [index - 1].Bottom);
linearSet [index - 1] = linearSet [index];
}
}
linearSet [placePos] = tempLinear;
linearSet [placePos].Layout (linearSet[placePos].Left, orgTop,
linearSet[placePos].Right, orgBottom);
view.RemoveViews (0, view.ChildCount);
for (index = 0; index < linearSet.Count; index++) {
view.AddView(linearSet[index]);
}
}
break;
}
return true;
}
}
}
You missed to register listener to the Button click and override onClick
How to add another one consumer in my program? I trying this, but not working...
I find this post how to add consumers in multithreading , but its not what i need, becouse I dont need lock... And i need without class or something like that. Just with my code.. PLease help :)
private int occupiedBufferCount = 0;
private int occupiedBufferCount2 = 0;
int i = 0;
private void Producer()
{
int how_much_numbers = Convert.ToInt32(textBox3.Text);
using (StreamWriter writer = new StreamWriter("random_skaiciai.txt"))
{
for (i = 0; i < how_much_numbers; i++)
{
Monitor.Enter(this);
if ((occupiedBufferCount == 1) || (occupiedBufferCount2 == 1))
{
Monitor.Wait(this);
}
++occupiedBufferCount;
buffer = i;
Random rnd = new Random();
numbers = i;
//numbers = rnd.Next(nuo, iki);
writer.WriteLine(numbers + "");
prm = false;
fib = false;
Monitor.Pulse(this);
Monitor.Exit(this);
if (isCanceled == true)
break;
}
writer.Close();
Set_p(kiek);
}
}
private void Consumer1()
{
int how_much_numbers = Convert.ToInt32(textBox3.Text);
using (StreamWriter writer = new StreamWriter("Primary_numbers.txt"))
{
while (i < how_much_numbers)
{
Monitor.Enter(this);
if ((occupiedBufferCount == 0))
{
Monitor.Wait(this);
}
--occupiedBufferCount;
if (numbers != 0)
if (prime_num(numbers) == true)
{
writer.WriteLine(numbers + "");
}
prm = true;
Monitor.Pulse(this);
Monitor.Exit(this);
if (isCanceled == true)
break;
}
writer.Close();
}
}
private void Consumer2()
{
int how_much_numbers = Convert.ToInt32(textBox3.Text);
using (StreamWriter writer = new StreamWriter("fibon_Numbers.txt"))
{
while (i < how_much_numbers)
{
Monitor.Enter(this);
if ((occupiedBufferCount2 == 0))
{
Monitor.Wait(this);
}
--occupiedBufferCount2;
if (numbers != 0)
if (isfibonaci(numbers) == true)
writer.WriteLine(numbers + "");
Monitor.Pulse(this);
Monitor.Exit(this);
if (isCanceled == true)
break;
}
writer.Close();
}
}
I am trying to code a multithreaded WebBrowser application.
The WebBrowser elements will just navigate to a given URL,
wait until it loads and then
click a button or
submit the form.
This should happen in a loop forever.
I'm using Microsoft Visual Studio 2010 and Windows Forms
Here's my code:
//added windows form 30 webbrowser object
//and now assigning them to an webbrowser array
wbList[0] = webBrowser1; wbList[1] = webBrowser2; wbList[2] = webBrowser3;
wbList[3] = webBrowser4; wbList[4] = webBrowser5; wbList[5] = webBrowser6;
wbList[6] = webBrowser7; wbList[7] = webBrowser8; wbList[8] = webBrowser9;
//etc. until:
wbList[29] = webBrowser30;
for (int i = 0; i < 30; i++)
{
wbList[i].ScriptErrorsSuppressed = true;
wbList[i].NewWindow += new CancelEventHandler(wb_NewWindow);
}
//********************************** creating threads here
Thread[] AllThread = new Thread[100];
int irWhichWbb = 0;
for (int nn = irDirectPostCount; nn < irNumber+1; nn++)
{
AllThread[nn] = new Thread(new
ParameterizedThreadStart(this.MultiThreadWebBrowser));
AllThread[nn].Start(nn.ToString() + ";" + irWhichWbb.ToString());
irWhichWbb++;
}
Application.DoEvents();
for (int nn = 0; nn < irNumber+1; nn++)
{ AllThread[nn].Join(); }
//Multi thread function
void MultiThreadWebBrowser(object parameter)
{
string srParam = parameter.ToString();
int i = Convert.ToInt32 (srParam.Substring(0,(srParam.IndexOf(";"))));
int irWhichWb = Convert.ToInt32(srParam.Substring(srParam.IndexOf(";")+1));
string hdrs = "Referer: http://www.xxxxxxxxx.com/xxxxxxxxxx.aspx";
try
{
wbList[irWhichWb].Navigate(srVotingList[i, 0], "_self", null, hdrs);
}
catch { }
try { waitTillLoad(irWhichWb); }
catch { }
waitTillLoad3();
}
// wait until webbrowser navigate url loaded
private void waitTillLoad(int irWhichLoad)
{
WebBrowserReadyState loadStatus;
//wait till beginning of loading next page
int waittime = 100000;
int counter = 0;
while (true)
{
try
{
loadStatus = wbList[irWhichLoad].ReadyState;
Application.DoEvents();
if ((counter > waittime) ||
(loadStatus == WebBrowserReadyState.Uninitialized) ||
(loadStatus == WebBrowserReadyState.Loading) ||
(loadStatus == WebBrowserReadyState.Interactive))
{
break;
}
counter++;
}
catch { }
}
//wait till the page get loaded.
counter = 0;
while (true)
{
try
{
loadStatus = wbList[irWhichLoad].ReadyState;
Application.DoEvents();
if (loadStatus == WebBrowserReadyState.Complete)
{
break;
}
if (counter > 10000000)
break;
counter++;
}
catch { }
}
}
private void waitTillLoad3()
{
DateTime dtStart = DateTime.Now;
while (true)
{
if ((DateTime.Now - dtStart).TotalMilliseconds > 4000)
break;
Application.DoEvents();
}
}
You don't say what kind of failure you get: "doesn't work" is not a good description.
I would first try with just a single thread. Does that work?
You have empty catch blocks, so you are silently ignoring some error conditions. This may well by hiding a problem.