首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#多线程.abort() .suspend() .reusme()

C#多线程.abort() .suspend() .reusme()
EN

Stack Overflow用户
提问于 2017-09-06 20:16:04
回答 1查看 225关注 0票数 0

如何中止、暂停或恢复线程?

由于im使用.Abort()(对象引用未设置为对象实例)出现运行时错误。而对于.Resume().Suspend(),则存在一个错误。

我在我的Run()中尝试了一个Thread.Sleep(1000),但我意识到它不会工作,因为它不是所使用的线程的实例。

你知道我该怎么做吗?

thx

代码:

代码语言:javascript
复制
class FolderStats : IFolderStats
{
    Thread MyThread = null;
    private bool x;
    string Rootpath;
    List<string> MyList = new List<string>();
    Folder FD = new Folder();

    public void Connect(string rootpath)
    {

        Console.WriteLine(Statuses.Waiting);
        Thread.Sleep(1000);

        FD.Path = rootpath;
        Rootpath = rootpath;

        Console.WriteLine(Statuses.Connected);
        Thread.Sleep(1000);
    }

    public void Start()
    {
        MyThread = new Thread(Run);
        MyThread.Start();
        Console.WriteLine("Starting the Search");
    }          
    public void Stop()
    {
        MyThread.Abort();
        Console.WriteLine("Console Aborted. Please press Enter to Exit");
    }
    public void Pause()
    {
        this.x = false;
        PauseResume();
        Console.WriteLine("Console Paused.");
    }
    public void Resume()
    {
        this.x = true;
        PauseResume();
        Console.WriteLine("Console Resumed.");
    }
    private void PauseResume()
    {
        while (this.x == false)
        {
            Thread.Sleep(100);
        }
    }
    public void Run()
    {

        MyThread = new Thread(Start);
        if (!MyList.Contains(Rootpath))
        {
            MyList.Add(Rootpath);
            var subDirs = Directory.GetDirectories(Rootpath, "*");
            var Data = Directory.GetFiles(Rootpath, "*");

            foreach (string dir in subDirs)
            {
                Thread.Sleep(2000);
                Rootpath = dir;
                Console.WriteLine(dir);

                Run();
            }
            foreach (string file in Data)
            {
                Thread.Sleep(2000);
                if (!MyList.Contains(file))
                {
                    MyList.Add(file);
                    Console.WriteLine(file);
                }
            }
        }
        FD.NumberOfFiles = MyList.Count; 
    }
EN

回答 1

Stack Overflow用户

发布于 2017-09-06 20:28:55

不要使用Thread,而要使用Task。您可以运行新任务:

代码语言:javascript
复制
Task.Run(()=>...);

您可以使用CancellationToken/CancellationTokenSource来实现使您的任务可取消:

https://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

如果你想暂停你的任务,你可以尝试实现类似这样的东西:

https://blogs.msdn.microsoft.com/pfxteam/2013/01/13/cooperatively-pausing-async-methods/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46074998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档