如何将 JScript Closure 转换为 JScript 中的 .NET 委托?
我有一个“for”循环,必须转换数千个彼此不依赖的文件中的内容。代码是用 JScript 编写的。我想添加一些线程代码来在 CPU 之间分发文件,因为其他 CPU 似乎处于空闲状态。我尝试在 JScript 中使用 System.Threading.ThreadPool 类,特别是 QueueUserWorkItem 方法,但在运行时出现错误:
Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'Microsoft.JScript.Closure' to type 'System.Threading.WaitCallback'.
这是我的代码:
var conv = function MyConverter(arg1)
{
// do the work
};
ThreadPool.QueueUserWorkItem( WaitCallback(conv) );
如果我将代码更改为调用 'new WaitCallback(conv) ' 然后我得到这个 jsc.exe 编译器错误:
error JS1258: Delegates should not be explicitly constructed, simply use the method name
所以我尝试了:
ThreadPool.QueueUserWorkItem( conv );
但是然后我们又回到了上面完全相同的 InvalidCastException 。
I have a 'for' loop that has to transform stuff in thousands of files that don't depend on each other. The code is written in JScript. I would like to add some threading code to distribute the files among CPUs since the others appear to be idle. I'm trying to use the class System.Threading.ThreadPool, specifically the QueueUserWorkItem method, in JScript, but get an error at runtime that says:
Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'Microsoft.JScript.Closure' to type 'System.Threading.WaitCallback'.
Here is my code:
var conv = function MyConverter(arg1)
{
// do the work
};
ThreadPool.QueueUserWorkItem( WaitCallback(conv) );
If I change my code to to call 'new WaitCallback(conv)' then I get this jsc.exe compiler error:
error JS1258: Delegates should not be explicitly constructed, simply use the method name
So I tried that with:
ThreadPool.QueueUserWorkItem( conv );
But then we are back to exact same InvalidCastException above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是“全局”函数不能以这种方式用作委托。这是从它们创建的委托是使用以下事实创建的副作用:
其中第二个参数“Object”是要调用该方法的对象的实例。
您需要创建一个类来执行您想要执行的操作,例如:
这应该可以正常编译并运行,我使用 JSC 10.00.30319 来测试它。
您可以通过在类中创建几个实例变量,使用类实例来存储您计划在闭包中存储的任何状态(如果有)。
希望这有帮助。
The problem is that "global" functions cannot be used as delegates this way. This is a side effect of the fact that the delegates created from them are created using:
Where the second parameter "Object" is the instance of the object that the method will be invoked on.
You'll need to create a class to do what you are trying to do, something like:
This should compile and run fine, I used JSC 10.00.30319 to test it.
You can use the class instance to store whatever state you were planning on storing in the closure (if any) by creating a couple of instance variables in the class.
Hope this helps.