async Memorystream approach in c# to get data asyn

2019-09-10 05:44发布

My dashboard needs too much time to get data from database so I have to use async approach to handle this problem here is my code :

public async Task < Stream > LoadDashboard() {
   Stream s = new MemoryStream(Encoding.Default.GetBytes(Resource.Dashboard));
   s.Position = 0;
   return s;
}

private async void frmMaterialDashboard_Load(object sender, EventArgs e) {
   Stream dashboardData = await LoadDashboard();
   dashboardViewer1.LoadDashboard(dashboardData);

  //show UI components for user interact
}

My code doesn't work and I have to wait for data to come from the database. Should I add anything else ?

This part of code takes long time to load data

 Stream s = new MemoryStream(Encoding.Default.GetBytes(Resource.Dashboard));
 s.Position = 0;

I want to execute this part async. When my form is loaded I want to call LoadDashboard as a background task to get the data from database ,and the main thread show my user interface form .

The component link that I am using :

https://documentation.devexpress.com/#Dashboard/CustomDocument113927

1条回答
该账号已被封号
2楼-- · 2019-09-10 06:05

From what it looks like you have no actual async work you can do, you are reading a resource in to a memory stream. Putting the async keyword on somthing does nothing by itself, the function still runs just like it used to. If you want the work to happen in the background you have to tell it to work in the background by using a new thread.

//Get rid of this async stuff here.
public Stream LoadDashboard()
{

    Stream s = new MemoryStream(Encoding.Default.GetBytes(Resource.Dashboard));
    s.Position = 0;
    return s;

}

private async  void frmMaterialDashboard_Load(object sender, EventArgs e)
{
    //Start LoadDashboad in a background thread and await it.
    Stream dashboardData = await Task.Run(() => LoadDashboard());
    dashboardViewer1.LoadDashboard(dashboardData);

    //show UI components for user interact
}

Another option is to not copy the string to a memory stream and instead get the stream directly

private void frmMaterialDashboard_Load(object sender, EventArgs e)
{
    using (var dashboardStream = Resources.ResourceManager.GetStream("Dashboard"))
    {
        dashboardViewer1.LoadDashboard(dashboardStream);
    }

    //show UI components for user interact
}

I got rid of the async because DashboadViewer does not provide a way to call LoadDashboard from the background to the best of my knowledge. You will have to wait till it finishes loading or figure out how to get smaller data.

查看更多
登录 后发表回答