欢迎光临
个人技术文档整理

在 .net framework 代码迁移至 .net core 时需要注意 BeginInvoke 不再被支持

问题

 .net core使用BeginInvoke , 代码编译很正常,但是在运行过程中,一旦触发就会报异常

System.PlatformNotSupportedException:“Operation is not supported on this platform.”

 

解决方案

使用 Task.Run 来替换 BeginInvoke 即可

.net framework 

//.net framework

 Action action = Overtime;//方法
            IAsyncResult asyncResult = action.BeginInvoke(null, null);
            while (!asyncResult.IsCompleted)
            {
                Console.WriteLine("检测是否完成中...");
                Thread.Sleep(1000);
            }

.net core

//.net core
var task = Task.Run(() =>
            {
                Overtime();//一个耗时长的方法
            });

            while (!task.IsCompleted)
            {
                Console.WriteLine("检测是否完成中...");
                Thread.Sleep(1000);
            }

 

参考

https://devblogs.microsoft.com/dotnet/migrating-delegate-begininvoke-calls-for-net-core/

赞(1)