开发者

Why can't I use/cast an Action for/to a ThreadStart?

开发者 https://www.devze.com 2022-12-23 12:12 出处:网络
Both are delegates and have the same signature, but I can not use Action as ThreadStart. Why? Action doIt开发者_JAVA百科;

Both are delegates and have the same signature, but I can not use Action as ThreadStart.

Why?

Action doIt开发者_JAVA百科;
doIt = () => MyMethod("test");
Thread t;

t = new Thread(doIt);
t.Start();

but this seems to work:

Thread t;

t = new Thread(() => MyMethod("test"));
t.Start();


As others have noted, the problem is that delegate types are not "structural". That is, they do not have equivalence based on their "structure".

Now, this is arguably a good thing for some types. If you have

struct MyRectangle { int x; int y; int width; int height; ... }

and

struct YourRectangle { int x1; int y1; int x2; int y2; ... } 

obviously it would be a mistake to allow instances of MyRectangle to be assigned to variables of YourRectangle, just because they both consisted of four ints. The semantics of the ints are different and therefore the types are not equivalent.

The same is, in theory, true of delegates. You could have

delegate int Pure(string x);
delegate int Func(string x);

where a "pure" function is one with no side effects and the same output given the same input. Since every Pure is logically a Func, but every Func is not necessarily a Pure, there shouldn't be structural typing between them.

In practice of course the type system does not support notions like "pure function" very well. And in practice, the vast majority of attempts to convert between delegate types are perfectly safe: converting from a Func<int, bool> to a Predicate<int> and so on.

So, two things, one looking backwards and one looking forwards. Backwards: if we had to do it all over again, I think delegates would probably be structurally typed in the CLI. You don't always know what features are going to be useful when you design a brand new framework, and non-structural delegate types have thus far turned out to be not as useful as perhaps anticipated. Forwards: I expect to see more features in future versions of the CLR that enable more structural typing. The "no pia" feature in C# 4, for example, is about making two types that are semantically and structurally the same, but defined in different assemblies, logically unify structurally.


I believe this should work?

Action doIt;
doIt = () => MyMethod("test");
Thread t;

t = new Thread(doIt.Invoke);
t.Start();


The basic form of this error is:

delegate void d1();
delegate void d2();
d1 a;
d2 b;
b = a;

Error Cannot implicitly convert type 'ConsoleDemo1.d1' to 'ConsoleDemo1.d2'

So you could 'solve' your first sample by using the correct delegate type:

//Action doIt;
ThreadStart doIt;
doIt = () => MyMethod("test");
Thread t = new Thread(doIt);


The behaviour your are noticing is because Action is a type and the 'lambda' in your second, working example, is not.

Arguably, they are the same, but you are using a concrete framework type when using Action, whereas the compiler infers the signature of the lambda.

EDIT: to be clear:

Action is a delegate type, which is not a ThreadStart delegate, so while you can assign the lambda expression to both, you cannot use both to start a thread.

In the second example you are giving the compiler the opportunity to infer the type of delegate and, with no great surprise, it is able to assign the lamda expression to the type ThreadStart.


Delegates with the same signature are not the same in the eyes of the CLR - they are entirely different types.


Because thread start is a separate delegate type and Action cannot be converted to ThreadStart.

This case works because here your lambda is treated by compiler as ThreadStart:

Thread t;

t = new Thread(() => MyMethod("test"));
t.Start();


I think the following verbiage in section 26.3.1 of the C# Language Specification is important:

Similar to an anonymous-method-expression, a lambda-expression is classified as a value with special conversion rules. The value does not have a type but can be implicitly converted to a compatible delegate type. Specifically, a delegate type D is compatible with a lambda-expression L provided:
[List elided]

Which prevents code like this from compiling:

var doIt = () => MyMethod("test");    // CS0815

Which leads to:

Action<object> doIt = (o) => MyMethod("test");
t = new Thread((ParameterizedThreadStart)doIt);  // CS0030

Defeated by the compiler disallowing conversions from one delegate type to another, even if their signatures are compatible. Forcing:

ParameterizedThreadStart doIt = (o) => MyMethod("test");
t = new Thread(doIt);

Which compiles without trouble.


Irrelevant bonus feature: early usability tests on the first Apple Mac discovered a problem with the first version of the OK button on the dialogs that used a sans-serif font. Users were often clicking Cancel instead, with some visible anguish. After several interviews, one user finally admitted the problem: "I hate it when a computer calls me a Dolt!"

Well, a compiler calling you a dolt perhaps isn't that irrelevant :)


Try:

t = new Thread(new ThreadStart(doIt));

or

t = new Thread( ()=>MyMethod("test"));

You're trying to pass an argument of type "Action" to a constructor that takes a ThreadStart. There isn't an implicit conversion defined, so you need to manually invoke the ThreadStart constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消