如何静态code多线程运行? [英] How does static code run with multiple threads?

查看:126
本文介绍了如何静态code多线程运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读<一href="http://stackoverflow.com/questions/1511798/threading-from-within-a-class-with-static-and-non-static-methods">http://stackoverflow.com/questions/1511798/threading-from-within-a-class-with-static-and-non-static-methods和我在一个类似的情况。

I was reading http://stackoverflow.com/questions/1511798/threading-from-within-a-class-with-static-and-non-static-methods and I am in a similar situation.

我有拉的数据从资源和基于数据产生了一些运行时对象的静态方法。

I have a static method that pulls data from a resource and creates some runtime objects based on the data.

static class Worker{
    public static MyObject DoWork(string filename){
        MyObject mo = new MyObject();

        // ... does some work

        return mo;
    }
}

的方法,需要一段时间(在这种情况下,它是读取5-10mb文件),并返回一个对象。

The method takes awhile (in this case it is reading 5-10mb files) and returns an object.

我想利用这个方法,并用它在多线程的情况,所以我可以同时读取多个文件。设计问题/一旁指导,如何将多个线程访问此code?

I want to take this method and use it in a multiple thread situation so I can read multiple files at once. Design issues / guidelines aside, how would multiple threads access this code?

让我们说我有这样的事情...

Let's say I have something like this...

class ThreadedWorker {
    public void Run() {
        Thread t = new Thread(OnRun);
        t.Start();
    }

    void OnRun() {
        MyObject mo = Worker.DoWork("somefilename");

        mo.WriteToConsole();
    }
}

难道每个线程的静态方法运行,允许并行执行?

Does the static method run for each thread, allowing for parallel execution?

推荐答案

是的,该方法应该能够在多个线程中运行良好。你应该担心的唯一的事情是在访问多个线程在同一文件在同一时间。

Yes, the method should be able to run fine in multiple threads. The only thing you should worry about is accessing the same file in multiple threads at the same time.

这篇关于如何静态code多线程运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆