如何创建异步方法 [英] How to create an asynchronous method

查看:90
本文介绍了如何创建异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#应用程序中有简单的方法,它从FTP服务器中选择文件并进行解析并将数据存储在数据库中。我想要它是异步的,所以用户在应用程序上执行其他操作,一旦解析完成,他必须得到消息说解析完成。



我知道可以通过异步方法调用实现,但是我不知道该怎么做可以帮助我吗?

解决方案

您需要使用它们所包含的代理和 BeginInvoke 方法来异步运行另一种方法。由代理运行的方法的结束,您可以通知用户。例如:

  class MyClass 
{
private delegate void SomeFunctionDelegate(int param1,bool param2);
private SomeFunctionDelegate sfd;

public MyClass()
{
sfd = new SomeFunctionDelegate(this.SomeFunction);
}

private void SomeFunction(int param1,bool param2)
{
//做东西

//通知用户


public void GetData()
{
//做东西

sfd.BeginInvoke(34,true,null,null);
}
}

阅读 http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx


I have simple method in my C# app, it picks file from FTP server and parses it and stores the data in DB. I want it to be asynchronous, so that user perform other operations on App, once parsing is done he has to get message stating "Parsing is done".

I know it can achieved through asynchronous method call but I dont know how to do that can anybody help me please??

解决方案

You need to use delegates and the BeginInvoke method that they contain to run another method asynchronously. A the end of the method being run by the delegate, you can notify the user. For example:

class MyClass
{
    private delegate void SomeFunctionDelegate(int param1, bool param2);
    private SomeFunctionDelegate sfd;

    public MyClass()
    {
        sfd = new SomeFunctionDelegate(this.SomeFunction);
    }

    private void SomeFunction(int param1, bool param2)
    {
        // Do stuff

        // Notify user
    }

    public void GetData()
    {
        // Do stuff

        sfd.BeginInvoke(34, true, null, null);
    }
}

Read up at http://msdn.microsoft.com/en-us/library/2e08f6yc.aspx

这篇关于如何创建异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆