C#.NET 2.0中带有静态方法的异步调用 [英] Asynchronous call with a static method in C# .NET 2.0

查看:705
本文介绍了C#.NET 2.0中带有静态方法的异步调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.NET 2.0应用程序。在此应用程序中,我需要将数据传递回我的服务器。服务器公开了一个基于REST的URL,我可以将数据发布到该URL。当我将数据传递回服务器时,有时需要异步进行,而其他时候则需要阻塞调用。在异步调用的情况下,我需要知道调用何时完成。到目前为止,我都知道该怎么做。

I have a .NET 2.0 application. In this application, I need to pass data back to my server. The server exposes a REST-based URL that I can POST data to. When I pass data back to my server, I need to sometimes do so asynchronously, and other times I need a blocking call. In the scenario of the asynchronous call, I need to know when the call is completed. Everything up to this point I understand how to do.

我遇到麻烦的地方是,我正在研究的方法必须是静态的。它是我继承的代码,我不想重做所有这些代码。当前,我有两种静态方法:

Where I get into trouble is, the method that I am working on MUST be static. It's code I've inherited, and I'd rather not have to redo all of this code. Currently, I have two static methods:

public static string SendData (...) {
}

public static string SendDataAsync(...) {

}

返回的字符串是服务器的响应代码。静态部分让我很健康。我的屏蔽版本没有问题。但是,在异步调用的竞赛中,我不确定该怎么办。

The string returned is a response code from the server. The static part is giving me fits. It doesn't cause a problem in my blocking version. However, in the contest of the asynchronous call, I'm not sure what to do.

有人可以提供任何见解吗?

Does anyone have any insights they can provide?

推荐答案

这是C#5(IIRC)之前的通用异步模式。

This is the general async pattern before C# 5 (IIRC).

public static string SendData (...) {
}

public static IAsyncResult BeginSendData(..., AsyncCallback cb) {
   var f = new Func<..., string>(SendData);
   return f.BeginInvoke(..., cb, f);
}

public static string EndSendData(IAsyncResult ar) {
   return ((Func<..., string>) ar.AsyncState).EndInvoke(ar); 
}

用法:

BeginSendData(..., ar => 
   {
     var result = EndSendData(ar);
     // do something with result
   });

完整的控制台示例:

public static string SendData(int i)
{
    // sample payload
    Thread.Sleep(i);
    return i.ToString();
}

public static IAsyncResult BeginSendData(int i, AsyncCallback cb)
{
    var f = new Func<int, string>(SendData);
    return f.BeginInvoke(i, cb, f);
}

public static string EndSendData(IAsyncResult ar)
{
    return ((Func<int, string>)ar.AsyncState).EndInvoke(ar);
}

static void Main(string[] args)
{
    BeginSendData(2000, ar => 
        {
            var result = EndSendData(ar);
            Console.WriteLine("Done: {0}", result);
        });

    Console.WriteLine("Waiting");
    Console.ReadLine();
}

上面将显示:

Waiting
Done: 2000

这篇关于C#.NET 2.0中带有静态方法的异步调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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