• <bdo id='RhdDu'></bdo><ul id='RhdDu'></ul>

    <legend id='RhdDu'><style id='RhdDu'><dir id='RhdDu'><q id='RhdDu'></q></dir></style></legend>
    <i id='RhdDu'><tr id='RhdDu'><dt id='RhdDu'><q id='RhdDu'><span id='RhdDu'><b id='RhdDu'><form id='RhdDu'><ins id='RhdDu'></ins><ul id='RhdDu'></ul><sub id='RhdDu'></sub></form><legend id='RhdDu'></legend><bdo id='RhdDu'><pre id='RhdDu'><center id='RhdDu'></center></pre></bdo></b><th id='RhdDu'></th></span></q></dt></tr></i><div id='RhdDu'><tfoot id='RhdDu'></tfoot><dl id='RhdDu'><fieldset id='RhdDu'></fieldset></dl></div>

    1. <tfoot id='RhdDu'></tfoot>

      <small id='RhdDu'></small><noframes id='RhdDu'>

    2. 线程和委托——我不完全理解它们的关系

      Threads and delegates — I don#39;t fully understand their relations(线程和委托——我不完全理解它们的关系)
      <legend id='JzlKN'><style id='JzlKN'><dir id='JzlKN'><q id='JzlKN'></q></dir></style></legend>

      <tfoot id='JzlKN'></tfoot>

        <tbody id='JzlKN'></tbody>
      • <bdo id='JzlKN'></bdo><ul id='JzlKN'></ul>

              • <small id='JzlKN'></small><noframes id='JzlKN'>

                <i id='JzlKN'><tr id='JzlKN'><dt id='JzlKN'><q id='JzlKN'><span id='JzlKN'><b id='JzlKN'><form id='JzlKN'><ins id='JzlKN'></ins><ul id='JzlKN'></ul><sub id='JzlKN'></sub></form><legend id='JzlKN'></legend><bdo id='JzlKN'><pre id='JzlKN'><center id='JzlKN'></center></pre></bdo></b><th id='JzlKN'></th></span></q></dt></tr></i><div id='JzlKN'><tfoot id='JzlKN'></tfoot><dl id='JzlKN'><fieldset id='JzlKN'></fieldset></dl></div>

                本文介绍了线程和委托——我不完全理解它们的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                问题描述

                我写的代码有点像这样:

                I wrote a code that looks somewhat like this:

                Thread t = new Thread(() => createSomething(dt, start, finish) );
                t.Start();
                

                而且它有效(有时感觉就像有多个线程).

                And it works (sometimes it almost feel like there are multiple threads).

                但我没有使用任何委托.

                Yet I don't use any delegates.

                1. 没有代表的踏步是什么意思?
                2. 如果需要委托,请告诉我与委托的连接是什么以及如何建立的.

                推荐答案

                多线程非常复杂.您正在剪切和粘贴代码,甚至没有学习线程的最基本方面 - 如何启动线程.将 Web 上的某些内容粘贴到 UI 中以修复或调整控件是一回事.这是一种完全不同的过程.您需要研究该主题,编写所有自己的代码,并准确了解其工作原理,否则您只是在浪费时间.

                Multi-threading is very complex. You are cutting and pasting code without even learning anything about the most basic aspects of threading - how to start a thread. Pasting something off the web into a UI to fix or tweak a control, is one thing. This is a completely different kind of process. You need to study the subject, write all your own code, and understand exactly how it works, otherwise you are just wasting your time with this.

                委托是类型安全函数指针的 .NET 版本.所有线程都需要一个入口点才能开始执行.根据定义,当创建主线程时,它总是运行 Main() 作为它的入口点.您创建的任何其他线程都需要一个明确定义的入口点——一个指向它们应该开始执行的函数的指针.所以线程总是需要一个委托.

                A delegate is the .NET version of a type safe function pointer. All threads require an entry point to start execution. By definition when a primary thread is created it always runs Main() as it's entry point. Any additional threads you create will need an explicitly defined entry point - a pointer to the function where they should begin execution. So threads always require a delegate.

                委托也经常用于其他目的的线程,主要是回调.如果您希望线程报告一些信息,例如完成状态,一种可能性是创建一个线程可以使用的回调函数.再次,线程需要一个指针才能执行回调,因此委托也用于此.与入口点不同,这些是可选的,但概念是相同的.

                Delegates are often used in threading for other purposes too, mainly callbacks. If you want a thread to report some information back such as completion status, one possibility is to create a callback function that the thread can use. Again the thread needs a pointer to be able to execute the callback so delegates are used for this as well. Unlike an entry point these are optional, but the concept is the same.

                线程和委托的关系是辅助线程不能像主应用线程那样只调用方法,所以需要一个函数指针,而委托充当函数指针.

                The relationship between threads and delegates is secondary threads cannot just call methods like the primary app thread, so a function pointer is needed instead and delegates act as function pointers.

                您看不到委托,也没有创建委托,因为框架正在 Thread 构造函数中为您执行此操作.您可以传入要用于启动线程的方法,框架代码会为您创建一个指向该方法的委托.如果你想使用回调,你必须自己创建一个委托.

                You do not see the delegate and you did not create one because the framework is doing it for you in the Thread constructor. You can pass in the method you want to use to start the thread, and the framework code creates a delegate that points to this method for you. If you wanted to use a callback you would have to create a delegate yourself.

                这里是没有 lambda 表达式的代码.SomeClass 有一些处理需要很长时间并且在后台线程上完成.为了解决这个问题,创建了 SomeThreadTask,它包含进程代码和线程运行它所需的一切.当线程完成时,第二个委托用于回调.

                Here is code without lambda expressions. SomeClass has some processing that takes a long time and is done on background threads. To help with this the SomeThreadTask has been created, and it contains the process code and everything the thread needs to run it. A second delegate is used for a callback when the thread is done.

                真正的代码会更复杂,真正的类永远不必知道如何创建线程等,因此您将拥有管理器对象.

                Real code would be more complicated, and a real class should never have to know how to create threads etc so you would have manager objects.

                // Create a delegate for our callback function.
                public delegate void SomeThreadTaskCompleted(string taskId, bool isError);
                
                
                public class SomeClass
                {
                
                    private void DoBackgroundWork()
                    {
                        // Create a ThreadTask object.
                
                        SomeThreadTask threadTask = new SomeThreadTask();
                
                        // Create a task id.  Quick and dirty here to keep it simple.  
                        // Read about threading and task identifiers to learn 
                        // various ways people commonly do this for production code.
                
                        threadTask.TaskId = "MyTask" + DateTime.Now.Ticks.ToString();
                
                        // Set the thread up with a callback function pointer.
                
                        threadTask.CompletedCallback = 
                            new SomeThreadTaskCompleted(SomeThreadTaskCompletedCallback);
                
                
                        // Create a thread.  We only need to specify the entry point function.
                        // Framework creates the actual delegate for thread with this entry point.
                
                        Thread thread = new Thread(threadTask.ExecuteThreadTask);
                
                        // Do something with our thread and threadTask object instances just created
                        // so we could cancel the thread etc.  Can be as simple as stick 'em in a bag
                        // or may need a complex manager, just depends.
                
                        // GO!
                        thread.Start();
                
                        // Go do something else.  When task finishes we will get a callback.
                
                    }
                
                    /// <summary>
                    /// Method that receives callbacks from threads upon completion.
                    /// </summary>
                    /// <param name="taskId"></param>
                    /// <param name="isError"></param>
                    public void SomeThreadTaskCompletedCallback(string taskId, bool isError)
                    {
                        // Do post background work here.
                        // Cleanup the thread and task object references, etc.
                    }
                }
                
                
                /// <summary>
                /// ThreadTask defines the work a thread needs to do and also provides any data 
                /// required along with callback pointers etc.
                /// Populate a new ThreadTask instance with any data the thread needs 
                /// then start the thread to execute the task.
                /// </summary>
                internal class SomeThreadTask
                {
                
                    private string _taskId;
                    private SomeThreadTaskCompleted _completedCallback;
                
                    /// <summary>
                    /// Get. Set simple identifier that allows main thread to identify this task.
                    /// </summary>
                    internal string TaskId
                    {
                        get { return _taskId; }
                        set { _taskId = value; }
                    }
                
                    /// <summary>
                    /// Get, Set instance of a delegate used to notify the main thread when done.
                    /// </summary>
                    internal SomeThreadTaskCompleted CompletedCallback
                    {
                        get { return _completedCallback; }
                        set { _completedCallback = value; }
                    }
                
                    /// <summary>
                    /// Thread entry point function.
                    /// </summary>
                    internal void ExecuteThreadTask()
                    {
                        // Often a good idea to tell the main thread if there was an error
                        bool isError = false;
                
                        // Thread begins execution here.
                
                        // You would start some kind of long task here 
                        // such as image processing, file parsing, complex query, etc.
                
                        // Thread execution eventually returns to this function when complete.
                
                        // Execute callback to tell main thread this task is done.
                        _completedCallback.Invoke(_taskId, isError);
                
                
                    }
                
                }
                }
                

                这篇关于线程和委托——我不完全理解它们的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                相关文档推荐

                Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)
                Parameter count mismatch with Invoke?(参数计数与调用不匹配?)
                How to store delegates in a List(如何将代表存储在列表中)
                How delegates work (in the background)?(代表如何工作(在后台)?)
                C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)
                Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)
                  <tbody id='jPIGg'></tbody>
                • <bdo id='jPIGg'></bdo><ul id='jPIGg'></ul>

                  <legend id='jPIGg'><style id='jPIGg'><dir id='jPIGg'><q id='jPIGg'></q></dir></style></legend>

                    1. <small id='jPIGg'></small><noframes id='jPIGg'>

                      <i id='jPIGg'><tr id='jPIGg'><dt id='jPIGg'><q id='jPIGg'><span id='jPIGg'><b id='jPIGg'><form id='jPIGg'><ins id='jPIGg'></ins><ul id='jPIGg'></ul><sub id='jPIGg'></sub></form><legend id='jPIGg'></legend><bdo id='jPIGg'><pre id='jPIGg'><center id='jPIGg'></center></pre></bdo></b><th id='jPIGg'></th></span></q></dt></tr></i><div id='jPIGg'><tfoot id='jPIGg'></tfoot><dl id='jPIGg'><fieldset id='jPIGg'></fieldset></dl></div>

                        <tfoot id='jPIGg'></tfoot>