Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How can I identify the method that created the thread the current method is in?

I'm looking to identify the method that created the Thread that the current method is running in.

I would use new StackFrame(int).GetMethod().Name, but I'm in a new Thread at the time of running this, so this one is out.

An example of my code is below:

private void doSomething(object sender, EventArgs e)
{
    try
    {
        Thread thread = new Thread(new ParameterizedThreadStart(GenerateThreadMethod));
        thread.Start(new Dictionary<String, Object>() {
            { "date" , Convert.ToDateTime(monthCalendar.SelectionRange.Start)},
            { "path", myList[myListBox.SelectedIndex][1] }
        });
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}


private void GenerateThreadMethod(Object obj)
{
    Dictionary<String, Object> data = (Dictionary<String, Object>)obj;

    DateTime date = (DateTime)data["date"];
    String path = (String)data["path"];

    //I want to find the name of doSomething() right here

    doMoreThings(date, path);
}
like image 611
Joshua Schlichting Avatar asked Dec 19 '25 06:12

Joshua Schlichting


2 Answers

There's no built in way to do this. However you can pass an arbitrary object to your ParametrizedThreadStart delegate which can include whatever information you want to communicate including the calling method name.

like image 96
Joe Avatar answered Dec 21 '25 20:12

Joe


You can't identify the parent thread.

I've seen another suggest that you could try prefix the name of the new thread with the thread ID from the parent thread, and then create a constructor on the method you want to spawn that requires the thread ID from the parent.

You could then use this information to at least gain access to the parent thread, and go from there, but I'm not sure if that gets you close enough to what you were hoping to achieve.

like image 43
Shane Oborn Avatar answered Dec 21 '25 21:12

Shane Oborn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!