473,804 Members | 3,153 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

return a value from other thread?

92 New Member
okay so i have this situation:
i have to get round trip time (ping) from a IP, but if i do it in the UI thread it freezes if the ping is high, for example > 300, now to stop the UI to hang i made the ping in another thread, but how can i return value from the 2nd thread(the one pinging)?, i cant directly change the label because this code is in a dll, also even if i use delegates to make new thread (that support return value) the first thread wont stop for 2nd thread to give the return value, if i use thread.join then the whole idea of making ping in 2nd thread is useless because it just joines the 1st thread and freeze it...

any helps?
Sep 18 '09 #1
4 6078
GaryTexmo
1,501 Recognized Expert Top Contributor
I'm not 100% sure so I'll just throw this out there...

Have your ping thread call the delegate when it's done, then have the main thread, when it receives that call, update the label. The form runs normally.

Nothing should have to wait on anything, it just updates when it gets the call.

Does that make any sense? If you've tried that and it doesn't work, then sorry. I haven't done much work with delegates, but this seems like any other event driven process. The main form should update when it gets the data, but it shouldn't need to wait on it.
Sep 18 '09 #2
vishal1082
92 New Member
as i said, the code is in a DLL, so i just dont have a label here, i dont want the form calling for ping request to freeze

and once again gary, u r the one helping me, suspicious how always u help me.. lol
Sep 19 '09 #3
GaryTexmo
1,501 Recognized Expert Top Contributor
Suspicious? Nah... maybe I just troll this forum too much ;)

Anyway, are you saying the code to the ping program is in a DLL? If so, you should still be able to create a thread to run the ping process, then call a delegate when it returns.

Can you please provide more details?
Sep 19 '09 #4
vishal1082
92 New Member
well actually nvm it, i spent a hour while i was sleepy cuz i was up all night and wrote this code, works exactly as i want, it may look noobish or ugly cuz i wrote it at 7 AM waking all night...
Expand|Select|Wrap|Line Numbers
  1.         /// <summary>
  2.         /// Ping a web address or IP
  3.         /// </summary>
  4.         public sealed class Ping
  5.         {
  6.             #region variables & objects
  7.             Label lbl;
  8.             Form owner;
  9.             bool Continue = true;
  10.             string address = null;
  11.             #endregion
  12.  
  13.             #region constructor
  14.             /// <summary>
  15.             /// Ping a web address or IP
  16.             /// </summary>
  17.             /// <param name="Address">The Web Address or IP Address</param>
  18.             /// <param name="Caller">The Form that is calling this class</param>
  19.             public Ping(string Address, Form Caller)
  20.             {
  21.                 address = Address;
  22.                 owner = Caller;
  23.                 ThreadStart starter = delegate { pingip(); };
  24.                 Thread pinger = new Thread(starter);
  25.                 pinger.Start();
  26.             }
  27.             #endregion
  28.  
  29.             #region events
  30.  
  31.             #region events
  32.             void lbl_TextChanged(object sender, EventArgs e)
  33.             {
  34.                 string[] pingip = lbl.Text.Split('|');
  35.                 try { owner.Invoke((MethodInvoker)delegate { try { PingResult(Convert.ToInt32(pingip[0]), pingip[1]); } catch { } }); }
  36.                 catch { }
  37.             }
  38.             #endregion
  39.  
  40.             #region custom events
  41.             #region handlers
  42.             /// <summary>
  43.             /// PingResult Event Handler
  44.             /// </summary>
  45.             /// <param name="Ping">The ping result</param>
  46.             /// <param name="IP">IP being pinged</param>
  47.             public delegate void PingHandler(int Ping, string IP);
  48.             /// <summary>
  49.             /// Error Event Handler
  50.             /// </summary>
  51.             public delegate void ErrorHandler(Exception ex);
  52.             #endregion
  53.  
  54.             #region event declare
  55.             /// <summary>
  56.             /// Event raised when we get result of the ping.
  57.             /// </summary>
  58.             public event PingHandler PingResult;
  59.             /// <summary>
  60.             /// Event raised when some error occurs.
  61.             /// </summary>
  62.             public event ErrorHandler OnError;
  63.             #endregion
  64.             #endregion
  65.  
  66.             #endregion
  67.  
  68.             #region methods
  69.  
  70.             #region public
  71.             /// <summary>
  72.             /// Stop pinging the address given
  73.             /// </summary>
  74.             public void StopPing()
  75.             {
  76.                 Continue = false;
  77.             }
  78.             #endregion
  79.  
  80.             #region private
  81.             private void pingip()
  82.             {
  83.                 try
  84.                 {
  85.                     lbl = new Label();
  86.                     lbl.TextChanged += new EventHandler(lbl_TextChanged);
  87.                     while (Continue)
  88.                     {
  89.                         System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
  90.                         PingReply reply = ping.Send(address);
  91.                         try { lbl.Text = reply.RoundtripTime.ToString() + "|" + reply.Address.ToString(); }
  92.                         catch { lbl.Text = reply.RoundtripTime.ToString() + "|Error getting IP"; }
  93.                     }
  94.                     return;
  95.                 }
  96.                 catch (Exception ex) { owner.Invoke((MethodInvoker)delegate { try { OnError(ex); } catch { } }); }
  97.             }
  98.             #endregion
  99.  
  100.             #endregion
  101.         }
Sep 19 '09 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

2
1707
by: Tee | last post by:
Hi, Can we use thread.start on a function that has return value? I have a function that will take sometimes to run and it will return a string value, and I want to use thread.start to call this function and get the string, is this possible? Thanks,
27
2676
by: Maximus | last post by:
Hi, I was just wondering, is it good to use return without arguments in a void function as following: void SetMapLayer() { if( !Map ) return; layer = LAYER_MAP; }
2
25677
by: Leo Jay | last post by:
Dear all, i would like to get the return value of all threads e.g. def foo(num): if num>10: return 1 elif num>50: return 2
1
4696
by: Jack Addington | last post by:
I have a 3rd party object that fires an itemchanged event when someone edits some data on a form. This event has a custom eventArgs that has a field called ActionCode. In the code of the event, if you set this ActionCode to various values the control will respond in various ways (reject, reject change field, accept, etc). I am trying to understand exactly how that works as I am trying to extend the control and add more processing s...
14
3483
by: dcassar | last post by:
I have had a lively discussion with some coworkers and decided to get some general feedback on an issue that I could find very little guidance on. Why is it considered bad practice to define a public member with a return type that is derived from System.Exception? I understand the importance of having clean, concise code that follows widely-accepted patterns and practices, but in this case, I find it hard to blindly follow a standard...
22
4046
by: semedao | last post by:
Hi , I am using asyc sockets p2p connection between 2 clients. when I debug step by step the both sides , i'ts work ok. when I run it , in somepoint (same location in the code) when I want to receive 5 bytes buffer , I call the BeginReceive and then wait on AsyncWaitHandle.WaitOne() but it is signald imidiatly , and the next call to EndReceive return zero bytes length , also the buffer is empty. here is the code: public static byte...
3
1494
by: chance | last post by:
I want my thread method to return a String. However, the compiler is saying that the best overloaded method match for System.Threading.Thread has some invalid arguments. Not sure what I need to change here. public String generateNOV(string xmlParms) { Thread novThread = new Thread(delegate() tia,
1
3479
by: Chris Roth | last post by:
I've been working with boost::threads to do some multithreading in my code and have run into some questions that I haven't been able to find answers to. I'll include some sample code to illustrate my questions. #include <boost/thread/thread.hpp> #include <iostream> using namespace std;
7
10329
by: Terry Olsen | last post by:
How do I get this to work? It always returns False, even though I can see "This is True!" in the debug window. Do I have to invoke functions differently than subs? Private Delegate Function IsLvItemCheckedDelegate(ByVal ClientID As Integer) As Boolean Private Function IsLvItemChecked(ByVal ClientID As Integer) As Boolean If lvServers.InvokeRequired = True Then lvServers.Invoke(New IsLvItemCheckedDelegate(AddressOf IsLvItemChecked),...
0
9708
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9587
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9161
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5527
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5662
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3827
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2998
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.