="公共语言运行库检测到无效的程序。"???? 是微软的bug吗?

本文介绍了一种在Windows应用程序中遇到System.InvalidProgramException异常的处理方法。通过具体代码示例,详细展示了如何使用委托和Invoke机制来更新UI线程中的控件属性,从而避免因跨线程操作引发的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

用户代码未处理 System.InvalidProgramException
  Message="公共语言运行库检测到无效的程序。"
  Source="WindowsApplication1"
  StackTrace:
       在 WindowsApplication1.Winvoker.Invokess[T](Control ctrl, Invokes`1 i, T value)
       在 WindowsApplication1.Form1.Set() 位置 D:\我的文档\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\Form1.cs:行号 25
       在 System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
       在 System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
       在 System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)

 

 

 

ExpandedBlockStart.gif代码
using System;
using System.Collections.Generic;

using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }

        
private void button1_Click(object sender, EventArgs e)
        {
            
new Pixysoft.MultiThread.AsyncMethodHelper(Set).Do();
        }

        
private void Set()
        {
            Winvoker.Invokess
<string>(label1, SetText, "asdf");

        }

        
private void SetText(string mes)
        {
            label1.Text 
= "sdf";
        }
    }

    
public class Winvoker
    {
        
public delegate void Invokes<T>(T value);

        
private delegate void DInvokes<T>(Control ctrl, Invokes<T> i, T value);

        
public static void Invokess<T>(Control ctrl, Invokes<T> i, T value)
        {
            
if (ctrl.InvokeRequired)
                ctrl.Invoke(
new DInvokes<T>(Invokess<T>), new object[] { ctrl, i, value });
            
else
                i(value);
        }
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值