简体   繁体   English

任务中用作Func参数的静态或非静态方法 <TResult> C#中的构造函数?

[英]Static or non-static methods used as the Func parameter in a Task<TResult> constructor in C#?

I am writing a set of classes all derived from a base class. 我正在编写一组全部从基类派生的类。 I want to be able to run multiple Task threads. 我希望能够运行多个任务线程。 Can the Func() used in the constructor of the Task be an instance method or does it have to be a class static method? Task的构造函数中使用的Func()是实例方法还是必须是类静态方法? If it is an instance method, can multiple Tasks be started using the same non-static method? 如果是实例方法,是否可以使用同一非静态方法启动多个任务?

You seem to be conflating static and non static methods with thread safety , for lack of a better term... thread safety is probably as imprecise as a term can be, but it'll work in the present context. 您似乎正在将静态方法和非静态方法与线程安全性混为一谈,因为缺少更好的术语了…… 线程安全性可能不尽如人意,但可以在当前环境下使用。 This is the completely wrong thing to ask, so unlearn whatever you think you know about the supposedly inbred safety of static members. 要问这是完全错误的事情,因此,请不要对静态成员的所谓近交安全性有任何了解。

The rule is that what you are asking is safe(+) as long as its safe to call that same method concurrently. 规则是您要问的是安全的(+) ,只要可以安全地同时调用相同的方法即可。 When is this safe? 什么时候安全? Well, in broad terms, when the method only writes or reads local variables, only reads immutable shared data or there is some sort of synchronization implemented that allows it to read and/or write concurrently to shared data. 好吧,从广义上讲,当该方法仅写入或读取局部变量时,仅读取不可变的共享数据,或者实现了某种同步,使其可以同时读取和/或写入共享数据。

(+) Understand safe as the condition where your code will do what you expect it to do. (+)将安全理解为代码将执行您期望的操作的条件。

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

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