简体   繁体   English

如何从另一个类访问实例化的对象?

[英]How to access instantiated objects from another class?

I want to terminate the thread thr1 in Program Class from another class, I created a PoC code as shown below to demonstrate it better. 我想终止另一个类的程序类中的线程thr1,我创建了一个PoC代码,如下所示,以更好地演示它。 Assume my Program class is as below: 假设我的程序类如下:

public class Program
    {
        public static Thread thr1;
        public static void Main(string[] args)
        {
            Thread thr1= new Thread(() => Class1.DoSomething(param1,param2));
            thr1.Start();
            Thread.Sleep(1000);
            Test.Exec();

        }
    }

and this is my Test class: 这是我的测试课:

public class Test
{
    public static void Exec()
    {
        Program.thr1.Abort();
        Program.thr1= new System.Threading.Thread(() => Class1.DoSomething(param1, param2));
        Program.thr1.Start();
    }
}

What I actually want to do is to terminate the thr1 in class Program by the Exec method in Test class and reassign with different parameters and start it again. 我实际上想要做的是通过Test类中的Exec方法终止Program类中的thr1,并用不同的参数重新分配并重新启动它。 Is this possible? 这可能吗?

EDITED: Maybe I should have asked how to access instantiated object from another class? 编辑:也许我应该问过如何从另一个类访问实例化的对象?

Solution, @Karan Mentioned: 解决方案,@ Karan提及:

Replacing 更换

Thread thr1= new Thread(() => Class1.DoSomething(param1,param2));

with

thr1 = new Thread(() => Class1.DoSomething(param1,param2));

It should work as you've expected. 它应该可以按预期工作。

Edit 编辑

It was not working because in code declaring Thread thr1 inside Main which creating new local instance and not accessible to other classes. 它不起作用,因为在代码中在Main内部声明了Thread thr1 ,从而创建了新的本地实例并且其他类无法访问。

As your global object is static it will always give you same reference. 由于您的全局对象是静态的,因此它将始终为您提供相同的引用。 So assigning as thr1 = new Thread(() => Class1.DoSomething(param1,param2)); 因此分配为thr1 = new Thread(() => Class1.DoSomething(param1,param2)); will work fine. 会很好的工作。

As a general advice element avoid Thread Abort. 作为一般建议,请避免线程中止。 It does not result in graceful shutdown and can lead to all kinds of issues. 它不会导致正常关机,并且可能导致各种问题。 Most importantly make sure your thread is not responsible for keeping any relevant data intact. 最重要的是,确保您的线程不负责保持任何相关数据完整。 Thread.Abort will result in a ThreadAbortException being thrown and often does not result in what you would want to happen in all circumstances. Thread.Abort将导致引发ThreadAbortException,并且通常不会导致您在所有情况下都希望发生。 If you do not control the code launched in the thread you may not have another option, but if you do, do not use this mechanism. 如果您不控制在线程中启动的代码,则可能没有其他选择,但是如果这样做,请不要使用此机制。

Consider using something like this. 考虑使用类似这样的东西。 (Note the relevant part is you being able to gracefully terminate the work you are doing on the worker thread (sometimes this is difficult): (请注意,相关的部分是您可以正常终止正在工作线程上执行的工作(有时很难):

This is a C# 7.2 console app (as it has an async main method). 这是一个C#7.2控制台应用程序(因为它具有异步main方法)。

Just create this as a Console App to test, but if you do run it from an actual command line as VS sometimes doesn't play nice with CTRL-C interruption. 只需将其创建为要测试的控制台应用程序即可,但是如果您从实际的命令行运行它,因为VS有时会因CTRL-C中断而无法正常运行。

internal class Program
{
    private static async Task Main(string[] args)
    {
        var cts = new CancellationTokenSource();
        Console.WriteLine("Press CTRL-C to STOP!");
        Console.CancelKeyPress += (sender, eventArgs) => cts.Cancel();
        var longRunningTask = Task.Run(() => DoSomethingLongRunning(cts.Token));

        while (!longRunningTask.IsCompleted)
        {
            await Task.Delay(50, cts.Token);
        }
    }

    private static async Task DoSomethingLongRunning(CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            await Task.Delay(1000, token);
            Console.WriteLine("Doing Something");
        }
    }
}

Try this 尝试这个

public class Program
{
    public static Thread thr1;
    public static void Main(string[] args)
    {
        thr1= new Thread(() => Class1.DoSomething(param1,param2));
        thr1.Start();
        Thread.Sleep(1000);
        Test.Exec();

    }
}

Test class 测试班

public class Test
{
    public static void Exec()
    {
         Program.thr1.Abort();
         Program.thr1= new System.Threading.Thread(() => Class1.DoSomething(param1, param2));
        Program.thr1.Start();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从另一个 class 访问对象数组 - How to access an array of objects from another class 如何使用另一种形式实例化的类中的方法? - How can I use method from an class instantiated in another form? 从另一个类调用实例化方法 - Invoking an instantiated method from another class 如何从另一个类(ApplicationContext)显示已实例化(运行)的Form1类 - how to show already instantiated (running) class Form1 from another class (ApplicationContext) 如何从游戏对象列表中删除游戏 object,其中每个游戏对象都是实例化的“棋子”或 class - How do I remove a game object from a list of game objects where each gameobject is an instantiated 'piece' or a class C# Razor 页面,从实例化的 class 访问变量,实例化自另一个 class,实例化自 model,非常基本的问题 - C# Razor Pages, Accessing variable from an instantiated class instantiated from another class that is instantiated from model, very basic question 将运行时实例化的对象从一个场景加载到Unity中的另一个场景 - Loading objects instantiated during runtime from one scene to another in Unity 访问通过同级控件实例化的对象 - Access objects instantiated by sibling control 如何从一个类访问另一个类的成员? - How to access member of another class from a class? 如何通过XAML实例化对象? - How are objects instantiated by XAML?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM