【发布时间】:2010-04-07 20:59:34
【问题描述】:
我需要在我的类“Invoke()”中实现与 Control.Invoke() 具有相同行为的方法。
因此,当我从与创建实例的线程不同的线程中处理我的 InvokableEntity 类的实例时,我将能够调用 invokableEntity.Invoke(delegate ) 和 delegate 将在创建 InvokableEntity 的线程实例的上下文中执行。
是的,我已经阅读了this 的问题,它对我没有帮助 =(
请看一下他的代码,它说明了我尝试为事件处理程序实现描述的行为(CustomProcessor_ProgressChanged 方法应该从订阅事件的线程执行,但我不能这样做):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ComponentModel;
using System.Windows.Forms;
namespace MultiThread
{
class Program
{
private static CustomProcessor customProcessor = new CustomProcessor();
static void Main(string[] args)
{
Console.WriteLine("Worker was run from thread: {0}", Thread.CurrentThread.ManagedThreadId);
customProcessor.ProgressChanged += new EventHandler(CustomProcessor_ProgressChanged);
Thread workerThread = new Thread(customProcessor.Process);
AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(null);
//SynchronizationContext context = SynchronizationContext.Current;
workerThread.Start(asyncOperation);
Console.ReadLine();
}
static void CustomProcessor_ProgressChanged(object sender, EventArgs e)
{
Console.WriteLine("Custom ProgressChanged was handled in thread: {0}", Thread.CurrentThread.ManagedThreadId);
}
}
class CustomProcessor
{
public event EventHandler ProgressChanged;
public void RaiseProcessChanged(object o)
{
Console.WriteLine("RaiseProgressChanged was handled in thread: {0}", Thread.CurrentThread.ManagedThreadId);
if (this.ProgressChanged != null)
{
this.ProgressChanged(this, EventArgs.Empty);
}
}
public void Process(object asyncOperation)
{
Console.WriteLine("CustomProcessor.Process method was executed in thread: {0}", Thread.CurrentThread.ManagedThreadId);
AsyncOperation asyncOperationInternal = (AsyncOperation)asyncOperation;
asyncOperationInternal.Post(this.RaiseProcessChanged, null);
//SynchronizationContext context = (SynchronizationContext) asyncOperation;
//context.Send(s => this.RaiseProcessChanged(null), null);
//this.RaiseProcessChanged(new object());
}
}
}
谢谢!
【问题讨论】:
-
为什么这个问题(+一些好的答案)对你没有帮助?
-
它对我不起作用,我无法获得可行的解决方案。调用总是在不同的线程中执行 =(
-
来了,非常感谢您的关注!
标签: .net multithreading