[英]Using await with Task.Run but UI still hangs for a few seconds?
我正在使用SAP .NET Connector 3.0並嘗試使用單獨的線程登錄,因此我可以讓UI顯示一種登錄動畫。
我正在使用Async和Await來啟動登錄,但是在登錄期間UI會掛起大約10秒鍾。
這是代碼,它粗糙,因為我正在快速起草一個程序。
async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Busy.Visibility = System.Windows.Visibility.Visible; // Shows progress animation
if (await SAPLogin()) // Waits for login to finish, will always be true at the moment
{
await GetData(); // does things with sap
Busy.Visibility = System.Windows.Visibility.Collapsed; // Hides progress animation
}
}
private Task<bool> SAPLogin()
{
bool LoggedIn = true;
return Task.Run(() =>
{
Backend = new BackendConfig();
RfcDestinationManager.RegisterDestinationConfiguration(Backend);
SapRfcDestination = RfcDestinationManager.GetDestination(MyServer); // MyServer is just a string containing sever name
SapRap = SapRfcDestination.Repository;
BapiMD04 = SapRap.CreateFunction("MD_STOCK_REQUIREMENTS_LIST_API");
BapiMD04.SetValue("WERKS", "140");
return LoggedIn;
});
}
我只能想象Task中的某些東西正在使用UI?
編輯1:抱歉忘了解釋GetData()
作用。 GetData()
在SAP中運行各種報告(大量代碼)。 在視覺上,我知道它何時出現,因為我的小登錄動畫將從“登錄”變為“抓取數據”。 當我看到UI掛起時,我看到它正處於“登錄”階段。 登錄動畫有一個簡單的循環旋轉。 這將在整個登錄過程中停止,然后在大約5秒后繼續。
編輯2:懸掛似乎在這條線上出現
SapRfcDestination = RfcDestinationManager.GetDestination(MyServer);
編輯3:在我看到UI掛起的位置暫停應用程序時添加了線程照片。
據推測,里面什么也沒有GetData
或Task.Run
拉姆達內SAPLogin
試圖回調與UI線程Dispatcher.Invoke
, Dispatcher.BeginInvoke
或Dispatcher.InvokeAsync
。 首先檢查這種可能性。
然后,嘗試更改您的代碼,如下所示。 注意如何Task.Factory.StartNew
與TaskCreationOptions.LongRunning
是用來代替Task.Run
以及如何GetData
被卸載(盡管它已經async
,所以介意.Unwrap()
在這里)。 如果這有幫助,請單獨嘗試每個更改,以查看哪個特別有用,或者它是否是兩者的組合。
async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Busy.Visibility = System.Windows.Visibility.Visible; // Shows progress animation
if (await SAPLogin()) // Waits for login to finish, will always be true at the moment
{
//await GetData(); // does things with sap
await Task.Factory.StartNew(() => GetData(),
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default).Unwrap();
Busy.Visibility = System.Windows.Visibility.Collapsed; // Hides progress animation
}
}
private Task<bool> SAPLogin()
{
bool LoggedIn = true;
return Task.Factory.StartNew(() =>
{
Backend = new BackendConfig();
RfcDestinationManager.RegisterDestinationConfiguration(Backend);
SapRfcDestination = RfcDestinationManager.GetDestination(MyServer); // MyServer is just a string containing sever name
SapRap = SapRfcDestination.Repository;
BapiMD04 = SapRap.CreateFunction("MD_STOCK_REQUIREMENTS_LIST_API");
BapiMD04.SetValue("WERKS", "140");
return LoggedIn;
},
CancellationToken.None,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.