locked
Async/Await Question RRS feed

  • Question

  • I want to run two methods together in order to reduce delay and write to a label on a form once the methods have both completed.  Here is my syntax, but it produces an error of The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

    How can I overcome this error?  Below is syntax:

    namespace TestingAsyncAwait
    {
        public partial class HabibInman
        {
            private DataSet ds1 = new DataSet();
            private DataSet ds2 = new DataSet();
    		
    		private void Main()
    		{
    			var method1 = RunSql();
    			var method2 = RunSql1();
    			await System.Threading.Tasks.WhenAll(method1, method2);
    			WriteToLabel();
    		}
    		async System.Threading.Tasks.Task<DataSet> method1()
    		{			
    			ds2 = //Run SQL Query that takes roughly 90 seconds
    			return ds2;
    		}
    		async System.Threading.Tasks.Task<DataSet> method2()
    		{
    			ds1 = //Run SQL Query that takes roughly 120 seconds
    			return ds1;
    		}
    		private void writetolabel()
    		{
    			lblonetwothree.Text = ds1+"........................"+ds2;
    		}
    	}
    }


    Monday, March 7, 2016 9:33 PM

Answers

  • try this:

        class Program
        {
            static void Main (string[] args)
            {
                Task<DataSet> t1 = new Task<DataSet> (() =>
                {
                    DataSet ds = null;
                    // do something here to set ds
                    return ds;
                });
    
                Task<DataSet> t2 = new Task<DataSet> (() =>
                {
                    DataSet ds = null;
                    // do something here to set ds
                    return ds;
                });
    
    
                Task.WaitAll (t1, t2);
     
            }
     
        }

    Tuesday, March 8, 2016 12:22 AM