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

问题描述

我做一些测试用C#5.0新的异步模式(异步/等待)我有理解异步方法的调用方式有问题。

I do some tests with the new asynchronous pattern of C# 5.0 (async/await) I have a problem with understanding how the asynchronous methods are called.

考虑到这一点code:

Considering this code :

private async Task<string> DownloadAsync()
    {
        progress.ProgressChanged += (s, e) =>
            {
                progressBar1.Value = e.value;
            };

            return await DownloadSomething(myurl, progress);

    }

private async void CallDownloadAsync()
    {
        string text = await DownloadAsync();
        progressBar1.Value = 0;
        label1.Text = "Done!";
    }

private void button4_Click(object sender, EventArgs e)
    {
        CallDownloadAsync();
    }

所以,这code工作得很好。当我CLIC了将Button4一个下载任务开始,我的进度是正确更新。

So, this code works very well. When I clic the "button4" a downloading task begins and my ProgressBar is updated correctly.

不过,我想通过删除CallDownloadAsync()方法,这样的压缩我的code多一点点:

But, I'd like to compact my code a little bit more by removing CallDownloadAsync() method like this :

private void button4_Click(object sender, EventArgs e)
    {
        new Action(async () =>
        {
            string result = await Task.Run<string>(() => DownloadAsync());
        }).Invoke();
        label1.Text = "Running...";
    }

所以在这里,我想直接启动它调用DownloadAsync方法的动作,但是当我打我将Button4我对一个进度条的跨线程操作无效。所以,我不明白是什么动作()和我CallDownloadAsync()方法的调用之间的主要区别。

So here, I want to directly initiate an action which calls the DownloadAsync method but when I hit my Button4 I have a Cross-thread operation not valid on the progressBar. So I do not understand what is the main difference between the Action() and the call of my CallDownloadAsync() method.

推荐答案

不同的是,在前情况下,你从UI线程(上下文)调用 CallDownloadAsync()

The difference is that in former case you call CallDownloadAsync() from UI thread (context).

在后一种情况下, DownloadAsync()从发起任务其通常在由TPL(任务并行库)出UI线程的创建的不同线程中执行所谓的或者线程它创造。

In the latter case, DownloadAsync() is called from the initiated Task which is generally executed in a different thread created by TPL (Task Parallel Library) out of UI thread or threads created from it.

在WPF中,UI组件只能由一个专门的UI线程,或从下创建的(即具有相同的用户界面上下文)(其子)线程访问。

In WPF, UI components can be accessed only by a dedicated UI thread or (its children) threads created from under it (i.e with the same UI context).

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

08-16 06:51