简体   繁体   English

运行一个使用主线程中的方法的单独线程是否仍然在主线程上运行它? (C#)

[英]Will running a separate thread that uses a method from the main thread still run it on the main thread? (C#)

I'm working on a project that requires me to some multitasking on md5 check-sums. 我正在开发一个项目,需要我对md5校验和进行一些多任务处理。 I created a very simple way to handle the md5 check-sums by creating a new thread and using a method that allows me to reuse the different algorithms. 我创建了一个非常简单的方法来处理md5校验和,方法是创建一个新线程并使用一种允许我重用不同算法的方法。

Here's The code for my new thread: 这是我新线程的代码:

private readonly Thread md5Check_ = new Thread(new ThreadStart(md5Check));

Here's the handler for that thread: 这是该线程的处理程序:

private static void md5Check()
    {
        string config_integrity = GetChecksum(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "/file.txt", Algorithms.MD5,).ToLower();

    }

(This is written in the same MainWindow.xaml.cs file) Here's the GetChecksum method: (这是在相同的MainWindow.xaml.cs文件中编写的)这是GetChecksum方法:

public static string GetChecksum(string fileName, HashAlgorithm algorithm)
    {
        if (File.Exists(fileName))
        {
            using (var stream = new BufferedStream(File.OpenRead(fileName), 100000))
            {
                return BitConverter.ToString(algorithm.ComputeHash(stream)).Replace("-", string.Empty);
            }
        }
        else 
        {
            return "error";
        }
    }

And the algorithms: 算法:

 public static class Algorithms
    {
        public static readonly HashAlgorithm MD5 = new MD5CryptoServiceProvider();
        public static readonly HashAlgorithm SHA1 = new SHA1Managed();
        public static readonly HashAlgorithm SHA256 = new SHA256Managed();
        public static readonly HashAlgorithm SHA384 = new SHA384Managed();
        public static readonly HashAlgorithm SHA512 = new SHA512Managed();
        public static readonly HashAlgorithm RIPEMD160 = new RIPEMD160Managed();
    } 

I was wondering since the new thread (md5Check_) calls the getChecksum method on the main thread, if the actual calculations would be calculated on the new thread (md5check) or the main thread as if the file is 1GB or 2GB my application could appear to crash. 我想知道,因为新线程(md5Check_)调用主线程上的getChecksum方法,如果实际计算将在新线程(md5check)或主线程上计算,就好像文件是1GB或2GB我的应用程序可能看起来崩溃。

这将在新的单独线程上运行

使用当前代码(假设您在某处调用md5Check_.Start() ),您的代码将在您创建的线程(md5Check_)上运行。

Any method called from the thread will be executed on the calling thread unless you manually dispatch it via Dispatcher (in WPF) on other thread. 除非您通过其他线程上的Dispatcher(在WPF中)手动调度,否则从线程调用的任何方法都将在调用线程上执行

Also in your case you can verify yourself by using Thread.CurrentThread property in GetChecksum() method to see on what thread it is currently executing. 在您的情况下,您可以通过在GetChecksum()方法中使用Thread.CurrentThread属性来验证自己,以查看它当前正在执行的线程。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM