473,569 Members | 2,834 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calling a function with in a thread

Hi all,

I want to call a function with some intial parameters with in a
thread. At the end of the function execution it should return a value
to the caller. Caller is outside the thread.

Example
function test (int a, int b);
{
int y = a=b;
return y;
}

how can i call this function and get the return ?

Thank you,
Pubduu
Jun 27 '08 #1
9 3242
Pubs <pu******@gmail .comwrote:
I want to call a function with some intial parameters with in a
thread. At the end of the function execution it should return a value
to the caller. Caller is outside the thread.
So what is the caller's thread doing at the time? Does it provide some
way to marshall calls back onto it (as, say, the UI threads in WinForms
and WPF both do)?

--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
Jun 27 '08 #2
On Jun 11, 6:54*pm, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
Pubs <pubud...@gmail .comwrote:
* *I want to call a function with some intial parameters with in a
thread. At the end of the function execution it should return a value
to the caller. Caller is outside the thread.

So what is the caller's thread doing at the time? Does it provide some
way to marshall calls back onto it (as, say, the UI threads in WinForms
and WPF both do)?

--
Jon Skeet - <sk...@pobox.co m>
Web site:http://www.pobox.com/~skeet*
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com
I am calling my function from the UI. Button press can call that
function. Function should be inside a thread since I dont want to lock
the interface until it is finished. But at the end of the function it
should return the value back to the button.

Jun 27 '08 #3
Thread constructor has an overload that takes ParameterizedTh readStart
delegate as one of its parameter. You can use that to pass an object from the
caller
The best way to return some value back to the caller is to set some value on
the passed Object.

Hope it helps.

Sujeet

"Pubs" wrote:
On Jun 11, 6:54 pm, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
Pubs <pubud...@gmail .comwrote:
I want to call a function with some intial parameters with in a
thread. At the end of the function execution it should return a value
to the caller. Caller is outside the thread.
So what is the caller's thread doing at the time? Does it provide some
way to marshall calls back onto it (as, say, the UI threads in WinForms
and WPF both do)?

--
Jon Skeet - <sk...@pobox.co m>
Web site:http://www.pobox.com/~skeet
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com

I am calling my function from the UI. Button press can call that
function. Function should be inside a thread since I dont want to lock
the interface until it is finished. But at the end of the function it
should return the value back to the button.

Jun 27 '08 #4
On Jun 11, 8:07*pm, Sujeet <Suj...@discuss ions.microsoft. comwrote:
Thread constructor has an overload that takes ParameterizedTh readStart
delegate as one of its parameter. You can use that to pass an object from the
caller
The best way to return some value back to the caller is to set some value on
the passed Object.

Hope it helps.

Sujeet

"Pubs" wrote:
On Jun 11, 6:54 pm, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
Pubs <pubud...@gmail .comwrote:
* *I want to call a function with some intial parameters with ina
thread. At the end of the function execution it should return a value
to the caller. Caller is outside the thread.
So what is the caller's thread doing at the time? Does it provide some
way to marshall calls back onto it (as, say, the UI threads in WinForms
and WPF both do)?
--
Jon Skeet - <sk...@pobox.co m>
Web site:http://www.pobox.com/~skeet
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com
I am calling my function from the UI. Button press can call that
function. Function should be inside a thread since I dont want to lock
the interface until it is finished. But at the end of the function it
should return the value back to the button.- Hide quoted text -

- Show quoted text -
Could u please show me some code or any tutorial ? I am still a
bigginer.

Pubudu
Jun 27 '08 #5
On Wed, 11 Jun 2008 17:07:00 -0700, Sujeet
<Su****@discuss ions.microsoft. comwrote:
Thread constructor has an overload that takes ParameterizedTh readStart
delegate as one of its parameter. You can use that to pass an object
from the
caller
The best way to return some value back to the caller is to set some
value on
the passed Object.
The "best way"? I disagree. In fact, that's likely to be the absolute
worst way, unless you combine with some sort of event-driven inter-thread
communication as well. Otherwise, the other thread can only detect the
completion by polling the value being set.

As far as the original question goes:

Based on the problem description so far, I think that the BackgroundWorke r
class is probably your best bet. Subscribe to the DoWork and
RunWorkerComple ted events, and the delegate method subscribed to each
event will be run on the correct thread: the DoWork handler will be run on
a background thread, and the RunWorkerComple ted handler will be run on the
original thread (the GUI thread in this case).

That is probably sufficient advice, but if you decide that for some reason
the BackgroundWorke r class isn't appropriate, here are some other details
(note that the BackgroundWorke r class is a special case of all of the
following, fully encapsulating the techniques described as part of the
basic functionality of the BackgroundWorke r class)...

The best way to deal with the "thread complete" scenario is to call a
method. If the code executing in the thread is part of the same class
that starts the thread (for example, a Form sub-class), then you can just
call some specific method within the class. Otherwise, it would probably
make more sense for the class containing the thread code to allow for the
calling class to provide a delegate to be called with the thread code
completes.

The usual way to do this latter approach is to declare an event on the
thread class, have the client subscribe to the event, and then raise the
event when the thread is done. An alternative would be, for example, to
simply allow the caller to pass a delegate directly, and then invoke the
delegate when the thread is done (this is basically what an event does
anyway, but in a more flexible, general-purpose way).

Now, to get the "completed" code to execute on a specific thread, you need
some way to marshal the execution onto that specific thread. Since you
are apparently trying to get back onto your main GUI thread, the most
appropriate mechanism for doing this would be to use the Control.Invoke( )
method. If the thread code is already fully "aware of" the GUI code (e.g.
it's actually part of the Form sub-class), then you might as well just
call Invoke() from within the thread code. Otherwise, it will probably
make more sense to have the thread call some specific method in the client
class (via the mechanisms described above), and let that method deal with
calling Invoke() on the appropriate instance.

As far as sample code goes, use Google or MSDN search to look for specific
topics on the use of BackgroundWorke r, Control.Invoke( ) and the C# "event"
keyword. There is no shortage of existing examples in MSDN, this
newsgroup, and a variety of other web sites.

Pete
Jun 27 '08 #6
On Jun 11, 8:41*pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Wed, 11 Jun 2008 17:07:00 -0700, Sujeet *

<Suj...@discuss ions.microsoft. comwrote:
Thread constructor has an overload that takes ParameterizedTh readStart
delegate as one of its parameter. You can use that to pass an object *
from the
caller
The best way to return some value back to the caller is to set some *
value on
the passed Object.

The "best way"? *I disagree. *In fact, that's likely to be the absolute *
worst way, unless you combine with some sort of event-driven inter-thread *
communication as well. *Otherwise, the other thread can only detect the *
completion by polling the value being set.

As far as the original question goes:

Based on the problem description so far, I think that the BackgroundWorke r*
class is probably your best bet. *Subscribe to the DoWork and *
RunWorkerComple ted events, and the delegate method subscribed to each *
event will be run on the correct thread: the DoWork handler will be run on*
a background thread, and the RunWorkerComple ted handler will be run on the*
original thread (the GUI thread in this case).

That is probably sufficient advice, but if you decide that for some reason*
the BackgroundWorke r class isn't appropriate, here are some other details *
(note that the BackgroundWorke r class is a special case of all of the *
following, fully encapsulating the techniques described as part of the *
basic functionality of the BackgroundWorke r class)...

The best way to deal with the "thread complete" scenario is to call a *
method. *If the code executing in the thread is part of the same class *
that starts the thread (for example, a Form sub-class), then you can just *
call some specific method within the class. *Otherwise, it would probably *
make more sense for the class containing the thread code to allow for the *
calling class to provide a delegate to be called with the thread code *
completes.

The usual way to do this latter approach is to declare an event on the *
thread class, have the client subscribe to the event, and then raise the *
event when the thread is done. *An alternative would be, for example, to*
simply allow the caller to pass a delegate directly, and then invoke the *
delegate when the thread is done (this is basically what an event does *
anyway, but in a more flexible, general-purpose way).

Now, to get the "completed" code to execute on a specific thread, you need*
some way to marshal the execution onto that specific thread. *Since you *
are apparently trying to get back onto your main GUI thread, the most *
appropriate mechanism for doing this would be to use the Control.Invoke( ) *
method. *If the thread code is already fully "aware of" the GUI code (e.g. *
it's actually part of the Form sub-class), then you might as well just *
call Invoke() from within the thread code. *Otherwise, it will probably *
make more sense to have the thread call some specific method in the client*
class (via the mechanisms described above), and let that method deal with *
calling Invoke() on the appropriate instance.

As far as sample code goes, use Google or MSDN search to look for specific*
topics on the use of BackgroundWorke r, Control.Invoke( ) and the C# "event"*
keyword. *There is no shortage of existing examples in MSDN, this *
newsgroup, and a variety of other web sites.

Pete
Thank you for the recommandations . I did not know about the DoWork. I
think that is appropriate for me.

Pubudu
Jun 27 '08 #7
Peter,
Yes I agree that this is not the best way considering a more uber level;
maybe I mistyped. I was just trying to get to the most trivial solution.
BackgroundWorke r should do the trick and so will a delegate that you can
call asynchronously.
But I think Pubs for your case BackgroundWorke r fits right.

Sujeet
"Pubs" wrote:
On Jun 11, 8:41 pm, "Peter Duniho" <NpOeStPe...@nn owslpianmk.com>
wrote:
On Wed, 11 Jun 2008 17:07:00 -0700, Sujeet

<Suj...@discuss ions.microsoft. comwrote:
Thread constructor has an overload that takes ParameterizedTh readStart
delegate as one of its parameter. You can use that to pass an object
from the
caller
The best way to return some value back to the caller is to set some
value on
the passed Object.
The "best way"? I disagree. In fact, that's likely to be the absolute
worst way, unless you combine with some sort of event-driven inter-thread
communication as well. Otherwise, the other thread can only detect the
completion by polling the value being set.

As far as the original question goes:

Based on the problem description so far, I think that the BackgroundWorke r
class is probably your best bet. Subscribe to the DoWork and
RunWorkerComple ted events, and the delegate method subscribed to each
event will be run on the correct thread: the DoWork handler will be run on
a background thread, and the RunWorkerComple ted handler will be run on the
original thread (the GUI thread in this case).

That is probably sufficient advice, but if you decide that for some reason
the BackgroundWorke r class isn't appropriate, here are some other details
(note that the BackgroundWorke r class is a special case of all of the
following, fully encapsulating the techniques described as part of the
basic functionality of the BackgroundWorke r class)...

The best way to deal with the "thread complete" scenario is to call a
method. If the code executing in the thread is part of the same class
that starts the thread (for example, a Form sub-class), then you can just
call some specific method within the class. Otherwise, it would probably
make more sense for the class containing the thread code to allow for the
calling class to provide a delegate to be called with the thread code
completes.

The usual way to do this latter approach is to declare an event on the
thread class, have the client subscribe to the event, and then raise the
event when the thread is done. An alternative would be, for example, to
simply allow the caller to pass a delegate directly, and then invoke the
delegate when the thread is done (this is basically what an event does
anyway, but in a more flexible, general-purpose way).

Now, to get the "completed" code to execute on a specific thread, you need
some way to marshal the execution onto that specific thread. Since you
are apparently trying to get back onto your main GUI thread, the most
appropriate mechanism for doing this would be to use the Control.Invoke( )
method. If the thread code is already fully "aware of" the GUI code (e.g.
it's actually part of the Form sub-class), then you might as well just
call Invoke() from within the thread code. Otherwise, it will probably
make more sense to have the thread call some specific method in the client
class (via the mechanisms described above), and let that method deal with
calling Invoke() on the appropriate instance.

As far as sample code goes, use Google or MSDN search to look for specific
topics on the use of BackgroundWorke r, Control.Invoke( ) and the C# "event"
keyword. There is no shortage of existing examples in MSDN, this
newsgroup, and a variety of other web sites.

Pete

Thank you for the recommandations . I did not know about the DoWork. I
think that is appropriate for me.

Pubudu
Jun 27 '08 #8
(agree that BackgroundWorke r is a easy way to get this done...)

Re ParameterizedTh readStart - my main gripe with this is that it only
allows one arg, and there is no compile-time safety.

I would much rather use an anon-method to do this (obviously you can
move as-much or as-little out to separate methods if it gets big...):

void SomeEventHandle r(object sender, EventArgs args)
{
// here running on UI thread
ThreadPool.Queu eUserWorkItem(d elegate
{
// here running on pool thread
int i = SomeFunction("f oo", "bar");
this.Invoke((Me thodInvoker)del egate
{
// here running as callback on UI thread
this.Text = i.ToString();
});
});
}

Marc

Jun 27 '08 #9
On Thu, 12 Jun 2008 00:25:31 -0700, Marc Gravell <ma**********@g mail.com
wrote:
(agree that BackgroundWorke r is a easy way to get this done...)

Re ParameterizedTh readStart - my main gripe with this is that it only
allows one arg, and there is no compile-time safety.
Well, you could always pass an array of objects. Still no type safety,
but beggars can't be choosers. :)
I would much rather use an anon-method to do this (obviously you can
move as-much or as-little out to separate methods if it gets big...):
And the example you posted (not that there's anything wrong with it, as
far as it goes) works fine with BackgroundWorke r too:

BackgroundWorke r bw = new BackgroundWorke r();
int i;

bw.DoWork += delegate { i = SomeFunction("f oo", "bar"); };
bw.RunWorkerCom pleted += delegate { this.Text = i.ToString(); };

That's assuming I understand my variable capturing rules correctly, and
"i" is the same variable in both delegate methods. Someone check my
work. :)

Pete
Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3362
by: Travis Berg | last post by:
I'm running into a problem when trying to perform a callback to a Python function from a C extension. Specifically, the callback is being made by a pthread that seems to cause the problem. If I call the callback from the parent process, it works fine. The PyObject is static, and holds the same value in both Parent and thread, so I'm at a...
2
9759
by: Tony Liu | last post by:
Hi, I want to get the name of the calling function of an executing function, I use the StackTrace class to do this and it seems working. However, does anyone think that there any side effect towards this approach such as how would it works in multi-thread. Thanks Tony
2
1478
by: Badrinath Mohan | last post by:
Hi All I am accessing a COM component using C#. When i access it through the standalone c# application it works fine.But when i call it using ASP .net application its not working . For example This is my COM function.. Myfunction(int *PNINPUT ,int nsize,int *PNOUTPUT) is the com function in the DLL.
15
11746
by: Bryan | last post by:
I have a multi-threaded C# console application that uses WMI (System.Management namespace) to make RPC calls to several servers (600+ ) and returns ScheduledJobs. The section of my code that performs the query is contained in a delegate function that I execute via a second thread. On 1 or 2 of the 600+ servers the query hangs. I've tried to...
2
3139
by: Geler | last post by:
A theoretical question: Sorry if its a beginner question. Here is a quote from the MSDN explaning the C/C++ calling convention.. It demonstrates that the calling function is responsible to clean the stack pointer and it does it by the command "add esp,8" after returning from the called function. My questions: 1. Is the stack pointer...
4
4788
by: Edwin Gomez | last post by:
I'm a C# developer and I'm new to Python. I would like to know if the concept of Asynchronous call-backs exists in Python. Basically what I mean is that I dispatch a thread and when the thread completes it invokes a method from the calling thread. Sort event driven concept with threads. Thanks. Ed Gomez
1
1392
by: | last post by:
I'm trying to think something through and am wondering if may have some suggestions. I am building a Windows service (VStudio 2005, C#) that uses a COM component to answer a telephone call(s). The aqpplication uses 6 trunk channels for the lines. What I need to do is initialize all 6 lines and set the event handler to witfor/answer the...
1
1741
by: SAL | last post by:
Hello, I'm developing this remoting app (.net 2.0) and I need to bring the server app's form to the front often. Since you can not do cross-thread communication on a form or control without using Invoke, I declared a delegate to handle the cross-thread call to bring the form forward. Here's my code: Delegate Sub BringMeFront() Public...
3
4694
by: Klaus | last post by:
Hi, I have an existing VC 6 MFC application which communicates asynchronly with a VC 2005 managed code dll. I use an unmanaged base class with virtual functions to access methods in the MFC application. Furthermore, I use a pointer to an unmanaged function to jump back into the managed dll. The managed part is basically a remoting...
0
7693
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...
0
7605
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...
0
7917
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8118
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...
0
7962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6277
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...
1
5501
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5217
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...
0
3651
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...

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.