简体   繁体   中英

Transform Async Task method target framework 4.5 to TargetFramework 2.0

I have SSO service that uses async Task<ActionResult> to get the URL

It works fine on my local environment but when I release on live I get following Error:

Server Error in '/XXXX Application.

"async void" Page events are unsupported in the current application configuration. To enable this, set the following configuration switch in Web.config: For more information, see http://go.microsoft.com/fwlink/?LinkId=252465 .

I have researched on this and apparently Async Task feature was developed for 4.0-4.5 .net framework. There was some different patterns or methodologies to do this in previous .net framework.

First prize would obviously to push for .Net 4.5 to be installed or at least .Net 4 . But since you're asking about .Net 2 , this probably isn't an option.

If your call made to the server blocks until complete and the work on the server is async, you can make use of the Thread class to delegate work in different threads.

Here are some thoughts ways of achieving this:

No return types, No parameters

var ts = new ThreadStart(DoWorkAsync);
new Thread(ts).Start();
...  
public void DoWorkAsync()
{
   // This happens on a different thread.
}

No return types, with parameters

int id = 1;
var pts = new ParameterizedThreadStart(DoWorkWithParamsAsync);
new Thread(pts).Start(id);
...
public void DoWorkWithParamsAsync(object obj)
{
    // This happens on a different thread.
    int id = (int)obj;
}

With return types (IAsyncResult)

You could use the BeginInvoke method an then use a specific delegate signature with a return type:

Func<int> returnsIntDel = DoWorkReturnIntAsync;
var asyncRes = returnsIntDel.BeginInvoke(null, null);
//... some other work on main thread here...
int returnedInt = returnsIntDel.EndInvoke(asyncRes);
Console.WriteLine("Done");
...
public int DoWorkReturnIntAsync()
{
    // This happens on a different thread.
    return 0;
}

Synchronizing between threads

If you run into any synchronization scenarios where Thread s need to communicate or wait for each other, there are Synchronization Primitive class available for these scenarios (images from filterdCode blog).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM