473,407 Members | 2,306 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,407 software developers and data experts.

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 3224
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.com>
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.comwrote:
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.com>
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 ParameterizedThreadStart
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.comwrote:
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.com>
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...@discussions.microsoft.comwrote:
Thread constructor has an overload that takes ParameterizedThreadStart
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.comwrote:
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.com>
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****@discussions.microsoft.comwrote:
Thread constructor has an overload that takes ParameterizedThreadStart
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 BackgroundWorker
class is probably your best bet. Subscribe to the DoWork and
RunWorkerCompleted 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 RunWorkerCompleted 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 BackgroundWorker class isn't appropriate, here are some other details
(note that the BackgroundWorker class is a special case of all of the
following, fully encapsulating the techniques described as part of the
basic functionality of the BackgroundWorker 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 BackgroundWorker, 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...@nnowslpianmk.com>
wrote:
On Wed, 11 Jun 2008 17:07:00 -0700, Sujeet *

<Suj...@discussions.microsoft.comwrote:
Thread constructor has an overload that takes ParameterizedThreadStart
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 BackgroundWorker*
class is probably your best bet. *Subscribe to the DoWork and *
RunWorkerCompleted 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 RunWorkerCompleted 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 BackgroundWorker class isn't appropriate, here are some other details *
(note that the BackgroundWorker class is a special case of all of the *
following, fully encapsulating the techniques described as part of the *
basic functionality of the BackgroundWorker 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 BackgroundWorker, 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.
BackgroundWorker should do the trick and so will a delegate that you can
call asynchronously.
But I think Pubs for your case BackgroundWorker fits right.

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

<Suj...@discussions.microsoft.comwrote:
Thread constructor has an overload that takes ParameterizedThreadStart
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 BackgroundWorker
class is probably your best bet. Subscribe to the DoWork and
RunWorkerCompleted 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 RunWorkerCompleted 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 BackgroundWorker class isn't appropriate, here are some other details
(note that the BackgroundWorker class is a special case of all of the
following, fully encapsulating the techniques described as part of the
basic functionality of the BackgroundWorker 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 BackgroundWorker, 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 BackgroundWorker is a easy way to get this done...)

Re ParameterizedThreadStart - 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 SomeEventHandler(object sender, EventArgs args)
{
// here running on UI thread
ThreadPool.QueueUserWorkItem(delegate
{
// here running on pool thread
int i = SomeFunction("foo", "bar");
this.Invoke((MethodInvoker)delegate
{
// 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**********@gmail.com
wrote:
(agree that BackgroundWorker is a easy way to get this done...)

Re ParameterizedThreadStart - 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 BackgroundWorker too:

BackgroundWorker bw = new BackgroundWorker();
int i;

bw.DoWork += delegate { i = SomeFunction("foo", "bar"); };
bw.RunWorkerCompleted += 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
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...
2
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...
2
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 ...
15
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...
2
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...
4
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...
1
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). ...
1
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...
3
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...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...

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.