【问题标题】:Communicate with threads from an MVC application?与 MVC 应用程序中的线程通信?
【发布时间】:2012-08-29 20:55:34
【问题描述】:

我创建了一个运行多个线程的服务。我不需要单独与每个线程进行通信,而是一次与所有线程进行通信。我找到了这个article,它允许通过处理程序进行通信。我使用 WCF 作为我的服务端点,想知道我是否可以与它而不是处理程序进行通信。以下是我在服务中所做的一些示例代码:

public class ThreadCoordinator
    {
        private int _numberOfThreads = 10;
        private List<Thread> _threads;

        public ThreadCoordinator()
        {
            _threads = new List<Thread>();
        }

        private void StartThreads()
        {
            for (int t = 0; t < _numberOfThreads; t++)
            {
                var st = new TheThread();
                var thread = new Thread(new ThreadStart(st.Run));
                _threads.Add(thread);
                thread.Start();
            }
        }

        public void RunThreads()
        {
            try
            {
                StartThreads();
            }
            finally
            {
                WaitForAllThreads();
                CloseAllConnections();
            }
        }

        private void WaitForAllThreads()
        {
            foreach (Thread t in _threads)
            {
                t.Join();
            }
        }


        private void CloseAllConnections()
        {
            //do some stuff to clean up resources
        }
    }

    internal class TheThread
    {
        public void Run()
        {
            //Do The work and update a global variable
            foreach(var person in somePersonList)
            {
                //do some work on that person 
                _someGlobalIntegerMember ++;
            }
        }
    }

我想要一个全局变量来跟踪所有线程正在处理多少数据。因此,随着每个线程不断更新的东西正在处理数据。更重要的是,我希望能够从客户端的命令中暂停所有线程。如果我执行 ajax 请求或从 MVC 提交表单并不重要。这个article 说明了如何暂停一个线程,但我不确定它是否可以应用于多个线程。

【问题讨论】:

  • 我强烈推荐你使用 TPL

标签: c# multithreading asp.net-mvc-3 asp.net-mvc-4


【解决方案1】:

您可以在线程安全模式下使用 Interlocked.Increment(ref toYourGlobalMember) 递增一个整数。

关于取消,或许你可以试试 TPL 和 Cancellation Tokens。

【讨论】:

  • 没问题@DDiVita,希望你能解决你取消线程的问题。我一直在对 TPL 进行一些研究,如果您选择这种方式,也许我可以为您提供更多帮助。
  • 我查看了 TPL 并认为它可能更合适,您知道我如何使用 TPL 实现相同的代码吗?我仍在研究它是如何工作的,因为我还没有使用它。
  • 使用 TPL,您可以使用 Parallel.ForEach() 方法创建新任务。它需要一个 Collection 和一个委托来为您的集合中的每个项目执行任务。如果需要,TPL 将创建新线程,它使用 ThreadPool,因此您不必担心创建新线程。如果要限制并发,可以在 System.Threading.Tasks.ParallelOptions 中设置 MaxDegreeOfParallelism。你可以在这里看到一个例子:msdn.microsoft.com/en-us/library/dd460720.aspx
  • 关于取消挂起的任务,这里有一个例子blogs.msdn.com/b/pfxteam/archive/2009/06/22/9791840.aspx
猜你喜欢
  • 2012-02-06
  • 2013-02-17
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 1970-01-01
  • 2012-01-11
  • 2017-07-06
  • 2014-12-20
相关资源
最近更新 更多