标签: invoke

使用来自C#中不同线程的Invoke访问类成员

注意:系列的一部分:C#:从另一个类访问表单成员以及如何从C#中的另一个cs文件访问表单对象.


你好,

想法是在TCP客户端接收/发送数据包时使用备忘录通知用户.

经过几次修复,最合适的解决方案就是这个

    public string TextValue
    {
        set
        {
            this.Memo.Text += value + "\n";
        }
    }
Run Code Online (Sandbox Code Playgroud)

这就是它被调用的方式

    var form = Form.ActiveForm as Form1;
    if(form != null)
        form.TextValue = "Test asdasd";
Run Code Online (Sandbox Code Playgroud)

但是,由于不安全的线程调用,调用代码会引发异常.我在msdn找到了一个解决方案,但我似乎无法获得他们在那里使用的方法.

这是我的翻拍,不起作用.

    private void SetTextMemo(string txt)
    {
        if(this.Memo.InvokeRequired)
        {
            this.Invoke(SetTextMemo,txt); //error here
        }
        else
        {
            this.Memo.Text += txt + "\n";
        }
    }
Run Code Online (Sandbox Code Playgroud)

错误:

参数'1':无法从'方法组'转换为'System.Delegate'

参数'2':无法从'string'转换为'object []'

基本上,我正在尝试使用Invoke从另一个线程访问备忘录(或者更可能是说,在备忘录中添加文本).我以前从未使用它,也许这就是为什么我误解了我的错误.

c# multithreading invoke winforms

2
推荐指数
1
解决办法
5545
查看次数

BackgroundWorker还需要调用Invoke吗?

C#中做一些工作的最后一个问题显示进度条?,人们建议使用BackgroundWorker.我认为在BackgroundWorkerDoWork方法中你可以直接更新GUI,但为什么需要使用调用此函数调用Invoke.

toolTip.SetToolTip(button, toolTipText);
Run Code Online (Sandbox Code Playgroud)

c# invoke backgroundworker

2
推荐指数
1
解决办法
5232
查看次数

甚至在UI线程上执行时的跨线程操作

我有一个函数,它向父控件添加一个控件,该控件从与创建控件的线程不同的线程调用.这是怎么回事:

1        delegate void AddControlToParentDelegate(Control child, Control parent);
2        private void addControlToParent(Control child, Control parent) {
3        if (parent.InvokeRequired) {
4            AddControlToParentDelegate d = new  AddControlToParentDelegate(addControlToParent);
5            this.Invoke(d, new object[] { child, parent });
6            } else {
7                parent.Controls.Add(child);
8            }
9        }
10    }
Run Code Online (Sandbox Code Playgroud)

这既可以正常工作,也parent.InvokeRequired可以正常child.InvokeRequired.然后,一旦执行第5行(现在d调用委托并且该函数应该在UI线程上运行.(对吗?))child第7行引发跨线程操作无效异常.为什么是这样?它已经在它创建的线程上运行了吗?

我设法通过添加额外的(child.InvokeRequired)检查来解决这个问题:

delegate void AddControlToParentDelegate(Control child, Control parent);
private void addControlToParent(Control child, Control parent) {
    if (parent.InvokeRequired) {
        AddControlToParentDelegate d = new AddControlToParentDelegate(addControlToParent);
        this.Invoke(d, …
Run Code Online (Sandbox Code Playgroud)

c# multithreading invoke winforms

2
推荐指数
1
解决办法
532
查看次数

如何使用带有C#/ .NET的Reflection实例化程序集中的类?

我有这个库编译为calc.dll.

namespace MyClass
{
    public class Calculator
    {
        public int Value1 {get; set;}
        public int Value2 {get; set;}
        public Calculator()
        {
            Value1 = 100;
            Value2 = 200;
        }

        public int Add(int val1, int val2)
        {
            Value1 = val1; Value2 = val2;
            return Value1 + Value2;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想实例化Calculate类而不链接到calc.dll.C#可以做到吗?我想出了这个代码,但我不知道如何实例化这个Calculator类.

using System;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;

namespace EX
{
    public class Code
    {
        public static void Test()
        {
            string path = Directory.GetCurrentDirectory();
            string target = …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection instantiation invoke

2
推荐指数
1
解决办法
1万
查看次数

收集被修改; 枚举操作可能无法执行.C#

我需要帮助.我正在和一个arraylist一起工作,突然间我得到了这个错误.

mscorlib.dll中发生了未处理的"System.InvalidOperationException"类型异常

附加信息:收集已修改; 枚举操作可能无法执行.

这是显示异常的代码...

foreach (PC_list x in onlinelist) {
  if ((nowtime.Subtract(x.time)).TotalSeconds > 5) {
    Invoke(new MethodInvoker(delegate {
      index = Main_ListBox.FindString(x.PcName);
      if(index != ListBox.NoMatches)
      Main_ListBox.Items.RemoveAt(index);
    }));
    onlinelist.Remove(x);
    //Thread.Sleep(500);
  }
}
Run Code Online (Sandbox Code Playgroud)

哪里

public class PC_list {
    public string PcName;
    public string ip;
    public string status;
    public string NickName;
    public DateTime time;

}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 在线列表是一个arraylist
  • nowtime和x.time是DateTime.

调用堆栈

mscorlib.dll!System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext() + 0x122 bytes    
BlueBall.exe!BlueBall.BlueBall.clean_arraylist() Line 74 + 0x1a8 bytes  C#
BlueBall.exe!BlueBall.BlueBall.server() Line 61 + 0x8 bytes C#
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x63 bytes   
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext …
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading invoke

2
推荐指数
1
解决办法
2万
查看次数

在后台工作者期间调用

我需要调用它:string input_ip_r = listView1.Items[lc].SubItems[1].Text; 所以我用过

if (InvokeRequired)
{
    this.Invoke(new MethodInvoker(function));
    return;
}
Run Code Online (Sandbox Code Playgroud)

这有效,但现在我把它放入BackgroundWorker并使用它

if (InvokeRequired)
{
    this.Invoke(new MethodInvoker(bw.RunWorkerAsync));
    return;
}
Run Code Online (Sandbox Code Playgroud)

它会给出一个错误,您一次只能运行BackgroundWorker一个错误.

那么我如何调用Backgroundworker

c# background invoke worker

2
推荐指数
2
解决办法
1万
查看次数

InvalidOperationException:Collection已被修改; 指的是哪个集合?

我经常发现它没有真正指定究竟是什么样的集合导致了这种类型的异常.这是真的还是应该是显而易见的?也许我只是不明白如何正确解释异常消息..

我特别想知道这个.它指的是什么系列?

事件委托的参数只是(对象发送者),并且引发的事件传递null参数.虽然引发事件的类本身继承了一个列表:

public class TimeSerie : List<BarData>
Run Code Online (Sandbox Code Playgroud)

这里是否清楚"集合"是指引发事件的对象,还是它可以是另一个对象?可以这么说,一个动态改变的方法的事件处理程序的集合?或者会创建一个不同的例外?

    ************** Exception Text **************
System.InvalidOperationException: 
Collection was modified; enumeration operation may not execute.
   at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
   at System.Windows.Forms.Control.Invoke(Delegate method, Object[] args)
   at System.Windows.Forms.Control.Invoke(Delegate method)
   at SomeNameSpace.SomeUserControl.InvokeOnUpdateHistory(Object sender) in D:\SomePath\SomeUserControl.cs:line 5179
   at OtherNameSpace.OtherClass.TimeSerie.HistoryUpdateEventHandler.Invoke(Object sender)
Run Code Online (Sandbox Code Playgroud)

UserControl中发生异常:

    public class SomeUserControl 

    private void InvokeOnUpdate(object sender)
    {
    this.Invoke(new GenericInvoker(Method));   // << Exception here!
    }

    private void Method() {...}
Run Code Online (Sandbox Code Playgroud)

编辑: 添加了一些代码.有点简化,但认为它包括相关位.

private void Method() 
{
            if (this.instrument == null) return;  
            UnRegisterTimeSerieHandlers(this.ts); …
Run Code Online (Sandbox Code Playgroud)

.net c# multithreading invoke invalidoperationexception

2
推荐指数
1
解决办法
1132
查看次数

c#:Stack在Invoke停止

在C#/ .net中,当发生错误时,堆栈将记录在Windows错误日志中.但是,我的应用程序有很多跨线程调用.堆栈跟踪似乎在每个Invoke(MarshalledInvoke)停止.

例如:

我的堆栈:

Exception Info: Facebook.FacebookApiException
Stack:
at System.Windows.Forms.Control.MarshaledInvoke(System.Windows.Forms.Control, System.Delegate, System.Object[], Boolean)
at System.Windows.Forms.Control.Invoke(System.Delegate, System.Object[])
at Test.TcpTest.InterpretData()
at Test.TcpTest.Incoming(System.String)
at Test.TcpTest.cLoop()
at System.Threading.ThreadHelper.ThreadStart_Context(System.Object)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Threading.ThreadHelper.ThreadStart()
Run Code Online (Sandbox Code Playgroud)

在堆栈中进一步执行的代码中发生异常.但是,堆栈每次都停在marshalledInvoke.

有什么我可以做的事情来继续调用堆栈?

c# controls tcp invoke

2
推荐指数
1
解决办法
91
查看次数

是否需要InvokeRequired?

我的同事喜欢这样做

if (!listbox1.InvokeRequired)
    listbox1.Items.Add(Container.error_message);
else
    listbox1.Invoke((MethodInvoker)delegate
    {
        listbox1.Items.Add(Container.error_message);
    });
Run Code Online (Sandbox Code Playgroud)

他为什么要检查InvokedRequired?仅使用此声明会更好吗?

    listbox1.Invoke((MethodInvoker)delegate
    {
        listbox1.Items.Add(Container.error_message);
    });
Run Code Online (Sandbox Code Playgroud)

c# invoke

2
推荐指数
1
解决办法
1133
查看次数

通过反射调用带有params参数的Generic方法

我试图通过反射调用接受单个params参数的泛型方法.当我选择它是非泛型的时,传递一个object []项似乎已经足够了,但是当我需要调用泛型方法时它不再起作用了.

var type = typeof (ClassWithGenericMethod);
var method = type.GetMethod("GenericMethod", BindingFlags.Instance | BindingFlags.Public);
var genericMethod = method.MakeGenericMethod(typeof(object));
var result = (bool)genericMethod.Invoke(new ClassWithGenericMethod(), new object[]{"param"});
Assert.IsTrue(result);
Run Code Online (Sandbox Code Playgroud)

被叫班:

public class ClassWithGenericMethod
{
    public bool GenericMethod<T>(params string[] input)
    {
        return input.Length == 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

在断言之前代码失败,出现以下异常:

"System.String"类型的对象无法转换为"System.String []"类型.

c# generics reflection invoke params

2
推荐指数
1
解决办法
1065
查看次数