且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在线程中执行时,方法无效,但在其他情况下有效-C#

更新时间:2023-11-14 08:29:10

我前段时间也遇到了类似的问题...屁股痛.

I had similar problem a while back... Pain in the butt.

您正在执行跨线程操作,这是不安全的.这就是它崩溃的原因.您对问题出在哪里绝对是正确的.

You are doing cross thread operations, that is not safe. That is the reason why it crashes. You are absolutely right about where you problem is.

以下是此线程操作的msdn文档 http://msdn.microsoft .com/en-us/library/ms171728.aspx

Here is msdn documentation on this thread operations http://msdn.microsoft.com/en-us/library/ms171728.aspx

您需要为mciSendString => mciSendStringCallBack添加委托定义

You need to add delegate definition for mciSendString => mciSendStringCallBack

delegate void mciSendStringCallBack(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr hwndCallback);

私有静态void playSong(字符串路径)中,您需要检查是否 InvokeRequired ,如果需要实例化回调并调用它.

In private static void playSong(String path) you need to check if InvokeRequired, if it is you need to instantiate callback and invoke it.

mciSendStringCallBack method = new mciSendStringCallBack(....); this.Invoke(method , new object[] { .....});

仔细阅读msdn站点上的示例,他们可以很好地演示其工作原理.

Look through the example on the msdn site, they do a good job demonstrating who it works.

-

您可能想尝试使用后台工作程序,它为您提供了多线程的处理方式,更易于使用.

You might want to try using background worker, it gives you multi threaded way of doing things, easier to work with.