2015-11-03 83 views
0

我想(沒有成功),異步調用的函數,並等待其返回值如何從任務中正確獲取函數返回值?

bool result = Task.Factory.StartNew(() => { return StupidFunction(someParameter); }).Result; 

if (result) 
    MessageBox.Show("Yes"); 
else 
    MessageBox.Show("No"); 

其中愚蠢功能是public static bool功能

和應用永遠掛起。

+2

那麼,是什麼'StupidFunction()'做什麼? –

+0

可能重複http://stackoverflow.com/questions/10920174/how-to-start-a-task-that-takes-a-parameter-and-returns-a-value –

+0

您是否在尋找'bool result =等待Task.Factory ...'? –

回答

0

解決了與

Task.Run(() => 
{ 
    if (StupidFunction(someParameter)) 
     Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => MessageBox.Show(Application.Current.MainWindow, "yes"))); 
    else 
     Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => MessageBox.Show(Application.Current.MainWindow, "no"))); 
}); 
+0

這將只適用於WPF應用程序,從OP不清楚,這是WPF或Winforms,但很高興你得到它解決。 –