C# 如何在C语言类库中编写异步方法#
我正试图用C#编写一个类库。我应该使用.NETFramework 3.0 我有一个将一种文件类型转换为另一种文件类型的方法。这需要时间:C# 如何在C语言类库中编写异步方法#,c#,api,delegates,asynchronous,C#,Api,Delegates,Asynchronous,我正试图用C#编写一个类库。我应该使用.NETFramework 3.0 我有一个将一种文件类型转换为另一种文件类型的方法。这需要时间: public bool ConvertFiles() { // Conversion takes a long time // After conversion, if conversion is successfull then I return true, // else I return false } 由于此方法将公开,所以
public bool ConvertFiles()
{
// Conversion takes a long time
// After conversion, if conversion is successfull then I return true,
// else I return false
}
由于此方法将公开,所以当API用户想要使用此功能时,我不应该因为此方法而阻止他的应用程序。e、 g:
//User calls my API functions
ApiClass api = new ApiClass;
api.ConvertFiles();
// user should not wait for ConvertFiles to finish
// user's codes should continue even if ConvertFiles is not finished!
因此,我理解它,我应该给API用户一个“异步方法”
到目前为止,我搜索了以下链接:
public bool ConvertFilesAsync()
{
MethodDelegate dlgt = ConvertFiles;
// Create the callback delegate.
AsyncCallback cb = MyAsyncCallback;
// Initiate the Asynchronous call passing in the callback delegate
// and the delegate object used to initiate the call.
IAsyncResult ar = dlgt.BeginInvoke();
}
private void MyAsyncCallback(IAsyncResult ar)
{
// Because you passed your original delegate in the asyncState parameter
// of the Begin call, you can get it back here to complete the call.
MethodDelegate dlgt = (MethodDelegate) ar.AsyncState;
// Complete the call.
bool conversion = dlgt.EndInvoke (ar) ;
}
当用户导入我的类库时,他将使用以下函数:
//User calls my API functions
ApiClass api = new ApiClass;
api.ConvertFilesAsync();
// Now user's codes continue even if ConvertFiles is not finished!
但他如何理解转换是否成功完成?在他的代码中,他应该知道文件转换已经完成了?我如何管理这个
Ps:我是代理和异步方法调用方面的新手也许您可以使用
BackgroundWorker类
您可以创建私有字段,如:
private BackgroundWorker backgroundWorker;
然后在构造函数中创建一个实例并启动它运行:
this.backgroundWorker = new BackgroundWorker();
this.backgroundWorker.WorkerSupportsCancellation = true;
this.backgroundWorkerr.DoWork += new DoWorkEventHandler(YourMethod);
this.backgroundWorker.RunWorkerAsync();
在您的方法中,您可以执行发送,然后添加一些委托
NET Framework提供了三种执行异步
操作:
异步编程模型(APM)模式(也称为IAsyncResult模式),其中异步操作需要开始和结束
End方法(例如,异步的BeginWrite和EndWrite
写入操作)。对于新用户,不再建议使用此模式
发展。有关详细信息,请参阅
基于事件的异步模式(EAP),它需要一个具有异步后缀的方法,还需要一个或多个事件Event
处理程序委托类型和EventArg派生类型。介绍了EAP
在.NET Framework 2.0中。不再建议将其用于新项目
发展。有关详细信息,请参阅
基于任务的异步模式(TAP),它使用单个方法表示异步模式的启动和完成
活动TAP是在.NET Framework 4中引入的,是
NET中异步编程的推荐方法
框架C#中的async和await关键字以及async和await
Visual Basic语言中的运算符为TAP添加了语言支持。对于
有关详细信息,请参阅
因为您使用的是.Net 3,所以可以使用APM和EAP
你可以在这里找到一个例子:谢谢你的回答,但我不明白。此代码段是否用于API?或者最终用户将使用此代码段来运行长时间运行的方法。它非常容易使用。以下是示例: