我是 C# 的新手,正在开发一个基于事件的系统来处理来自线程的输入。 UI 必须根据从线程收到的响应进行更新。我在其中一篇文章中找到并在表单上使用了 BeginInvoke。但是,我的问题是,
class CustomDispatcher
{
public void Routine1()
{}
public BeginInvoke()
{
// like in control.BeginInvoke((MethodInvoker)delegate{ Routine1(); });
// This should execute Routine1 asynchronously. This BeginInvoke will be called from a different thread.
}
}
当使用表单实例时,BeginInvoke 运行良好。但是,我不知道我是否可以将表单的这种调度功能模拟到我的类实例。
非常感谢任何帮助。
提前致谢。
请您参考如下方法:
一般来说,如果您正在制作一个新的 API,并且想要编写异步方法,我强烈建议您围绕 Task 设计您的 API。和 Task<T> 类。
这将允许它直接与 async 一起工作/await C# 5 中的支持。
在你的例子中,自 Routine1是一个 void 方法,您可以编写一个异步处理它的方法,即:
public Task Routine1Async()
{
// Perform the work asynchronously...
}
或者,使用 C# 5:
public async Task Routine1Async()
{
// Perform the work taking advantage of the await keyword...
await SomeOtherMethodAsync(); // etc
}
也就是说,如果这纯粹是为了调用 Task.Run或 Task.Factory.StartNew ,我会把它留在你的 API 之外,让调用者根据需要把它变成一个异步方法。我不建议制作仅包装同步 API 的异步 API。
