C# 如何使用异步委托?

C# 如何使用异步委托?,c#,asynchronous,delegates,C#,Asynchronous,Delegates,我有一个C#windows窗体应用程序。我的其中一个按钮具有此事件: private void btnNToOne_Click(object sender, EventArgs e) { int value = (int)numUpToThis.Value; textResult.Text = Program.asyncCall(value, 2).ToString(); } 它调用的方法是: public delegate in

我有一个C#windows窗体应用程序。我的其中一个按钮具有此事件:

    private void btnNToOne_Click(object sender, EventArgs e)
    {
        int value = (int)numUpToThis.Value;
        textResult.Text = Program.asyncCall(value, 2).ToString();
    }
它调用的方法是:

    public delegate int DelegateWithParameters(int numar, int tipAlgoritm);
    public static int asyncCall(int numar, int tipAlgoritm)
    {
        DelegateWithParameters delFoo = new DelegateWithParameters(calcPrim);
        IAsyncResult tag = delFoo.BeginInvoke(numar, tipAlgoritm, null, null);
        while (tag.IsCompleted == false)
        {
            Thread.Sleep(250);
        }
        int intResult = delFoo.EndInvoke(tag);
        return intResult;

    }

问题是它一直阻塞我的用户界面,所以我显然做错了什么。我应该如何使用异步委托?有什么提示吗?

这里有一个关于这种特殊情况的快速示例,当您需要类似的东西时,可以在一般情况下使用

首先,您不能将整个异步逻辑封装在方法中,因为返回语句不能提供结果,所以只能提供同步方法

static class MyUtils
{
    public static int CalcPrim(int numar, int tipAlgoritm)
    {
        // ...
    }
}
然后在表单中使用以下内容

private void btnNToOne_Click(object sender, EventArgs e)
{
    int value = (int)numUpToThis.Value;
    Action<int> processResult = result =>
    {
        // Do whatever you like with the result
        textResult.Text = result.ToString();
    }
    Func<int, int, int> asyncCall = MyUtils.CalcPrim;
    asyncCall.BeginInvoke(value, 2, ar =>
    {
        // This is the callback called when the async call completed
        // First take the result
        int result = asyncCall.EndInvoke(ar);
        // Note that the callback most probably will called on a non UI thread,
        // so make sure to process it on the UI thread
        if (InvokeRequired)
            Invoke(processResult, result);
        else
            processResult(result);
    }, null);
}

async/await
是一个选项,还是您坚持要
delegate
?看起来您只需要阅读一些异步编程的入门教程。解释整个编程范例超出了批准的范围,所以问题是。@IvanStoev,很遗憾,我必须使用委托。请检查这一点,特别是在异步调用完成时执行回调方法一节非常感谢@IvanStoev,与我使用的另一个例子相比,这个例子帮助我更好地理解我在做什么。它现在可以工作了,现在我必须弄清楚当它结束时如何返回结果。当你显式地强制一个方法在非UI线程中被调用时,它可能不会在非UI线程中被调用,它肯定会在非UI线程中被调用。检查它是否在非UI线程中是一种毫无意义的恩德沃尔,考虑到即使在UI线程中调用也可以正常工作,这就更没有意义了。尽管如此,从长远来看,丢弃一堆OP不会理解的代码是没有帮助的,它只会创建一个cargo cult编程实践,在未来导致更大的问题。现在,这是我需要的时候可以坚持的东西。非常感谢您的帮助。以上评论当然证明了我最后一句话的观点。@Servy大体上同意。但正如您可能看到的,我在向OP提供了指向MSDN文档的链接(带有类似示例)之后,以及在他确认已阅读该文档之后,才发布了代码,目的是帮助他将其与具体案例关联起来。当然我可能错了,但这提醒我很久以前我们都处于类似的情况。当然没有,所以我们必须自己弄清楚:——)@IvanStoev强迫某人从事货运邪教活动对他们是有害的。短期内它可能感觉良好,但从长远来看,由于缺乏对核心概念的理解,它只会导致更大、更复杂的问题。如果你真的想帮助他们,你就不会这么做。
private async void btnNToOne_Click(object sender, EventArgs e)
{
    int value = (int)numUpToThis.Value;
    int result = await Task.Run(() => MyUtils.CalcPrim(value, 2)); 
    textResult.Text = result.ToString();
}